diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3f0bf36f..d451c736 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 7.0.1 +current_version = 8.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 16f3dda0..37b3e913 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -34,7 +34,7 @@ jobs: - name: Setup Node uses: actions/setup-node@v1 with: - node-version: 18 + node-version: 20 - name: Install Semantic Release dependencies run: | diff --git a/README.md b/README.md index 9733d026..d09f490b 100755 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![Build and Test](https://github.com/watson-developer-cloud/python-sdk/workflows/Build%20and%20Test/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A"Build+and+Test") [![Deploy and Publish](https://github.com/watson-developer-cloud/python-sdk/workflows/Deploy%20and%20Publish/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A%22Deploy+and+Publish%22) -[![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net) [![Latest Stable Version](https://img.shields.io/pypi/v/ibm-watson.svg)](https://pypi.python.org/pypi/ibm-watson) [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) @@ -209,7 +208,7 @@ If you have issues with the APIs or have a question about the Watson services, s ## Configuring the http client (Supported from v1.1.0) -To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance +To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://requests.readthedocs.io/en/latest/api/) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python from ibm_watson import AssistantV1 diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index d0a1620e..b98b688b 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -28,7 +28,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional import json import sys @@ -81,18 +81,20 @@ def __init__( # Message ######################### - def message(self, - workspace_id: str, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - user_id: str = None, - nodes_visited_details: bool = None, - **kwargs) -> DetailedResponse: + def message( + self, + workspace_id: str, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + user_id: Optional[str] = None, + nodes_visited_details: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get response to user input. @@ -151,9 +153,11 @@ def message(self, if output is not None: output = convert_model(output) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='message', + ) headers.update(sdk_headers) params = { @@ -183,11 +187,13 @@ def message(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -196,11 +202,13 @@ def message(self, # Bulk classify ######################### - def bulk_classify(self, - workspace_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: + def bulk_classify( + self, + workspace_id: str, + *, + input: Optional[List['BulkClassifyUtterance']] = None, + **kwargs, + ) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -222,9 +230,11 @@ def bulk_classify(self, if input is not None: input = [convert_model(x) for x in input] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='bulk_classify', + ) headers.update(sdk_headers) params = { @@ -248,11 +258,13 @@ def bulk_classify(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -261,14 +273,16 @@ def bulk_classify(self, # Workspaces ######################### - def list_workspaces(self, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_workspaces( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List workspaces. @@ -293,9 +307,11 @@ def list_workspaces(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_workspaces') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_workspaces', + ) headers.update(sdk_headers) params = { @@ -313,29 +329,33 @@ def list_workspaces(self, headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_workspace(self, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_workspace( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create workspace. @@ -385,9 +405,11 @@ def create_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace', + ) headers.update(sdk_headers) params = { @@ -418,22 +440,26 @@ def create_workspace(self, headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_workspace(self, - workspace_id: str, - *, - export: bool = None, - include_audit: bool = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def get_workspace( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get information about a workspace. @@ -458,9 +484,11 @@ def get_workspace(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_workspace', + ) headers.update(sdk_headers) params = { @@ -479,31 +507,35 @@ def get_workspace(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_workspace(self, - workspace_id: str, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_workspace( + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update workspace. @@ -565,9 +597,11 @@ def update_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace', + ) headers.update(sdk_headers) params = { @@ -602,16 +636,22 @@ def update_workspace(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: + def delete_workspace( + self, + workspace_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete workspace. @@ -626,9 +666,11 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_workspace', + ) headers.update(sdk_headers) params = { @@ -644,29 +686,32 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_workspace_async( - self, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - **kwargs) -> DetailedResponse: + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + **kwargs, + ) -> DetailedResponse: """ Create workspace asynchronously. @@ -716,9 +761,11 @@ def create_workspace_async( if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace_async', + ) headers.update(sdk_headers) params = { @@ -748,32 +795,35 @@ def create_workspace_async( headers['Accept'] = 'application/json' url = '/v1/workspaces_async' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response def update_workspace_async( - self, - workspace_id: str, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - append: bool = None, - **kwargs) -> DetailedResponse: + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update workspace asynchronously. @@ -835,9 +885,11 @@ def update_workspace_async( if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace_async', + ) headers.update(sdk_headers) params = { @@ -871,22 +923,26 @@ def update_workspace_async( path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces_async/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def export_workspace_async(self, - workspace_id: str, - *, - include_audit: bool = None, - sort: str = None, - verbose: bool = None, - **kwargs) -> DetailedResponse: + def export_workspace_async( + self, + workspace_id: str, + *, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + verbose: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Export workspace asynchronously. @@ -915,9 +971,11 @@ def export_workspace_async(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='export_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='export_workspace_async', + ) headers.update(sdk_headers) params = { @@ -937,10 +995,12 @@ def export_workspace_async(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces_async/{workspace_id}/export'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -949,16 +1009,18 @@ def export_workspace_async(self, # Intents ######################### - def list_intents(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_intents( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List intents. @@ -990,9 +1052,11 @@ def list_intents(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_intents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_intents', + ) headers.update(sdk_headers) params = { @@ -1014,22 +1078,26 @@ def list_intents(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_intent(self, - workspace_id: str, - intent: str, - *, - description: str = None, - examples: List['Example'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_intent( + self, + workspace_id: str, + intent: str, + *, + description: Optional[str] = None, + examples: Optional[List['Example']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create intent. @@ -1061,9 +1129,11 @@ def create_intent(self, if examples is not None: examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_intent', + ) headers.update(sdk_headers) params = { @@ -1089,22 +1159,26 @@ def create_intent(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_intent(self, - workspace_id: str, - intent: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_intent( + self, + workspace_id: str, + intent: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get intent. @@ -1128,9 +1202,11 @@ def get_intent(self, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_intent', + ) headers.update(sdk_headers) params = { @@ -1149,24 +1225,28 @@ def get_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_intent(self, - workspace_id: str, - intent: str, - *, - new_intent: str = None, - new_description: str = None, - new_examples: List['Example'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_intent( + self, + workspace_id: str, + intent: str, + *, + new_intent: Optional[str] = None, + new_description: Optional[str] = None, + new_examples: Optional[List['Example']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update intent. @@ -1209,9 +1289,11 @@ def update_intent(self, if new_examples is not None: new_examples = [convert_model(x) for x in new_examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_intent', + ) headers.update(sdk_headers) params = { @@ -1239,17 +1321,23 @@ def update_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_intent(self, workspace_id: str, intent: str, - **kwargs) -> DetailedResponse: + def delete_intent( + self, + workspace_id: str, + intent: str, + **kwargs, + ) -> DetailedResponse: """ Delete intent. @@ -1267,9 +1355,11 @@ def delete_intent(self, workspace_id: str, intent: str, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_intent', + ) headers.update(sdk_headers) params = { @@ -1286,10 +1376,12 @@ def delete_intent(self, workspace_id: str, intent: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1298,16 +1390,18 @@ def delete_intent(self, workspace_id: str, intent: str, # Examples ######################### - def list_examples(self, - workspace_id: str, - intent: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_examples( + self, + workspace_id: str, + intent: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List user input examples. @@ -1339,9 +1433,11 @@ def list_examples(self, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_examples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_examples', + ) headers.update(sdk_headers) params = { @@ -1363,22 +1459,26 @@ def list_examples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_example(self, - workspace_id: str, - intent: str, - text: str, - *, - mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create user input example. @@ -1410,9 +1510,11 @@ def create_example(self, if mentions is not None: mentions = [convert_model(x) for x in mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_example', + ) headers.update(sdk_headers) params = { @@ -1438,22 +1540,26 @@ def create_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_example(self, - workspace_id: str, - intent: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get user input example. @@ -1476,9 +1582,11 @@ def get_example(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_example', + ) headers.update(sdk_headers) params = { @@ -1496,23 +1604,27 @@ def get_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_example(self, - workspace_id: str, - intent: str, - text: str, - *, - new_text: str = None, - new_mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + new_text: Optional[str] = None, + new_mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update user input example. @@ -1545,9 +1657,11 @@ def update_example(self, if new_mentions is not None: new_mentions = [convert_model(x) for x in new_mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_example', + ) headers.update(sdk_headers) params = { @@ -1573,17 +1687,24 @@ def update_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_example(self, workspace_id: str, intent: str, text: str, - **kwargs) -> DetailedResponse: + def delete_example( + self, + workspace_id: str, + intent: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete user input example. @@ -1604,9 +1725,11 @@ def delete_example(self, workspace_id: str, intent: str, text: str, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_example', + ) headers.update(sdk_headers) params = { @@ -1623,10 +1746,12 @@ def delete_example(self, workspace_id: str, intent: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1635,15 +1760,17 @@ def delete_example(self, workspace_id: str, intent: str, text: str, # Counterexamples ######################### - def list_counterexamples(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_counterexamples( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List counterexamples. @@ -1672,9 +1799,11 @@ def list_counterexamples(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_counterexamples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_counterexamples', + ) headers.update(sdk_headers) params = { @@ -1696,20 +1825,24 @@ def list_counterexamples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create counterexample. @@ -1735,9 +1868,11 @@ def create_counterexample(self, if text is None: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_counterexample', + ) headers.update(sdk_headers) params = { @@ -1762,21 +1897,25 @@ def create_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get counterexample. @@ -1798,9 +1937,11 @@ def get_counterexample(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_counterexample', + ) headers.update(sdk_headers) params = { @@ -1818,21 +1959,25 @@ def get_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_counterexample(self, - workspace_id: str, - text: str, - *, - new_text: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_counterexample( + self, + workspace_id: str, + text: str, + *, + new_text: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update counterexample. @@ -1858,9 +2003,11 @@ def update_counterexample(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_counterexample', + ) headers.update(sdk_headers) params = { @@ -1885,17 +2032,23 @@ def update_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_counterexample(self, workspace_id: str, text: str, - **kwargs) -> DetailedResponse: + def delete_counterexample( + self, + workspace_id: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete counterexample. @@ -1915,9 +2068,11 @@ def delete_counterexample(self, workspace_id: str, text: str, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_counterexample', + ) headers.update(sdk_headers) params = { @@ -1934,10 +2089,12 @@ def delete_counterexample(self, workspace_id: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1946,16 +2103,18 @@ def delete_counterexample(self, workspace_id: str, text: str, # Entities ######################### - def list_entities(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_entities( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entities. @@ -1987,9 +2146,11 @@ def list_entities(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_entities') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_entities', + ) headers.update(sdk_headers) params = { @@ -2011,24 +2172,28 @@ def list_entities(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_entity(self, - workspace_id: str, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - values: List['CreateValue'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_entity( + self, + workspace_id: str, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + values: Optional[List['CreateValue']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity. @@ -2065,9 +2230,11 @@ def create_entity(self, if values is not None: values = [convert_model(x) for x in values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_entity', + ) headers.update(sdk_headers) params = { @@ -2095,22 +2262,26 @@ def create_entity(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_entity(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_entity( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity. @@ -2134,9 +2305,11 @@ def get_entity(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_entity', + ) headers.update(sdk_headers) params = { @@ -2155,26 +2328,30 @@ def get_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_entity(self, - workspace_id: str, - entity: str, - *, - new_entity: str = None, - new_description: str = None, - new_metadata: dict = None, - new_fuzzy_match: bool = None, - new_values: List['CreateValue'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_entity( + self, + workspace_id: str, + entity: str, + *, + new_entity: Optional[str] = None, + new_description: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_fuzzy_match: Optional[bool] = None, + new_values: Optional[List['CreateValue']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity. @@ -2220,9 +2397,11 @@ def update_entity(self, if new_values is not None: new_values = [convert_model(x) for x in new_values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_entity', + ) headers.update(sdk_headers) params = { @@ -2252,17 +2431,23 @@ def update_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_entity(self, workspace_id: str, entity: str, - **kwargs) -> DetailedResponse: + def delete_entity( + self, + workspace_id: str, + entity: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity. @@ -2280,9 +2465,11 @@ def delete_entity(self, workspace_id: str, entity: str, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_entity', + ) headers.update(sdk_headers) params = { @@ -2299,10 +2486,12 @@ def delete_entity(self, workspace_id: str, entity: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2311,13 +2500,15 @@ def delete_entity(self, workspace_id: str, entity: str, # Mentions ######################### - def list_mentions(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_mentions( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity mentions. @@ -2342,9 +2533,11 @@ def list_mentions(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_mentions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_mentions', + ) headers.update(sdk_headers) params = { @@ -2363,10 +2556,12 @@ def list_mentions(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/mentions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2375,17 +2570,19 @@ def list_mentions(self, # Values ######################### - def list_values(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_values( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity values. @@ -2420,9 +2617,11 @@ def list_values(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_values') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_values', + ) headers.update(sdk_headers) params = { @@ -2445,25 +2644,29 @@ def list_values(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_value(self, - workspace_id: str, - entity: str, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value. @@ -2504,9 +2707,11 @@ def create_value(self, if value is None: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_value', + ) headers.update(sdk_headers) params = { @@ -2535,23 +2740,27 @@ def create_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_value(self, - workspace_id: str, - entity: str, - value: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value. @@ -2578,9 +2787,11 @@ def get_value(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_value', + ) headers.update(sdk_headers) params = { @@ -2599,27 +2810,31 @@ def get_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_value(self, - workspace_id: str, - entity: str, - value: str, - *, - new_value: str = None, - new_metadata: dict = None, - new_type: str = None, - new_synonyms: List[str] = None, - new_patterns: List[str] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + new_value: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_type: Optional[str] = None, + new_synonyms: Optional[List[str]] = None, + new_patterns: Optional[List[str]] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value. @@ -2673,9 +2888,11 @@ def update_value(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_value', + ) headers.update(sdk_headers) params = { @@ -2705,17 +2922,24 @@ def update_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_value(self, workspace_id: str, entity: str, value: str, - **kwargs) -> DetailedResponse: + def delete_value( + self, + workspace_id: str, + entity: str, + value: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value. @@ -2736,9 +2960,11 @@ def delete_value(self, workspace_id: str, entity: str, value: str, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_value', + ) headers.update(sdk_headers) params = { @@ -2755,10 +2981,12 @@ def delete_value(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2767,17 +2995,19 @@ def delete_value(self, workspace_id: str, entity: str, value: str, # Synonyms ######################### - def list_synonyms(self, - workspace_id: str, - entity: str, - value: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_synonyms( + self, + workspace_id: str, + entity: str, + value: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity value synonyms. @@ -2811,9 +3041,11 @@ def list_synonyms(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_synonyms') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_synonyms', + ) headers.update(sdk_headers) params = { @@ -2835,22 +3067,26 @@ def list_synonyms(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value synonym. @@ -2882,9 +3118,11 @@ def create_synonym(self, if synonym is None: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_synonym', + ) headers.update(sdk_headers) params = { @@ -2909,23 +3147,27 @@ def create_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value synonym. @@ -2951,9 +3193,11 @@ def get_synonym(self, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_synonym', + ) headers.update(sdk_headers) params = { @@ -2972,23 +3216,27 @@ def get_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - new_synonym: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + new_synonym: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value synonym. @@ -3021,9 +3269,11 @@ def update_synonym(self, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_synonym', + ) headers.update(sdk_headers) params = { @@ -3049,17 +3299,25 @@ def update_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_synonym(self, workspace_id: str, entity: str, value: str, - synonym: str, **kwargs) -> DetailedResponse: + def delete_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value synonym. @@ -3083,9 +3341,11 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_synonym', + ) headers.update(sdk_headers) params = { @@ -3103,10 +3363,12 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3115,15 +3377,17 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, # Dialog nodes ######################### - def list_dialog_nodes(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_dialog_nodes( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List dialog nodes. @@ -3151,9 +3415,11 @@ def list_dialog_nodes(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_dialog_nodes') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_dialog_nodes', + ) headers.update(sdk_headers) params = { @@ -3175,38 +3441,42 @@ def list_dialog_nodes(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create dialog node. @@ -3285,9 +3555,11 @@ def create_dialog_node(self, if actions is not None: actions = [convert_model(x) for x in actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3330,21 +3602,25 @@ def create_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get dialog node. @@ -3365,9 +3641,11 @@ def get_dialog_node(self, if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3385,39 +3663,43 @@ def get_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - new_dialog_node: str = None, - new_description: str = None, - new_conditions: str = None, - new_parent: str = None, - new_previous_sibling: str = None, - new_output: 'DialogNodeOutput' = None, - new_context: 'DialogNodeContext' = None, - new_metadata: dict = None, - new_next_step: 'DialogNodeNextStep' = None, - new_title: str = None, - new_type: str = None, - new_event_name: str = None, - new_variable: str = None, - new_actions: List['DialogNodeAction'] = None, - new_digress_in: str = None, - new_digress_out: str = None, - new_digress_out_slots: str = None, - new_user_label: str = None, - new_disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + new_dialog_node: Optional[str] = None, + new_description: Optional[str] = None, + new_conditions: Optional[str] = None, + new_parent: Optional[str] = None, + new_previous_sibling: Optional[str] = None, + new_output: Optional['DialogNodeOutput'] = None, + new_context: Optional['DialogNodeContext'] = None, + new_metadata: Optional[dict] = None, + new_next_step: Optional['DialogNodeNextStep'] = None, + new_title: Optional[str] = None, + new_type: Optional[str] = None, + new_event_name: Optional[str] = None, + new_variable: Optional[str] = None, + new_actions: Optional[List['DialogNodeAction']] = None, + new_digress_in: Optional[str] = None, + new_digress_out: Optional[str] = None, + new_digress_out_slots: Optional[str] = None, + new_user_label: Optional[str] = None, + new_disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update dialog node. @@ -3500,9 +3782,11 @@ def update_dialog_node(self, if new_actions is not None: new_actions = [convert_model(x) for x in new_actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3545,17 +3829,23 @@ def update_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_dialog_node(self, workspace_id: str, dialog_node: str, - **kwargs) -> DetailedResponse: + def delete_dialog_node( + self, + workspace_id: str, + dialog_node: str, + **kwargs, + ) -> DetailedResponse: """ Delete dialog node. @@ -3574,9 +3864,11 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3593,10 +3885,12 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3605,14 +3899,16 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, # Logs ######################### - def list_logs(self, - workspace_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_logs( + self, + workspace_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in a workspace. @@ -3632,6 +3928,8 @@ def list_logs(self, [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param int page_limit: (optional) The number of records to return in each page of results. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -3642,9 +3940,11 @@ def list_logs(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -3664,21 +3964,25 @@ def list_logs(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_all_logs(self, - filter: str, - *, - sort: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_all_logs( + self, + filter: str, + *, + sort: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in all workspaces. @@ -3711,9 +4015,11 @@ def list_all_logs(self, if not filter: raise ValueError('filter must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_all_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_all_logs', + ) headers.update(sdk_headers) params = { @@ -3730,10 +4036,12 @@ def list_all_logs(self, headers['Accept'] = 'application/json' url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3742,7 +4050,11 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3768,9 +4080,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3784,10 +4098,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3803,6 +4119,7 @@ class Sort(str, Enum): The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -3818,6 +4135,7 @@ class Sort(str, Enum): only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. """ + STABLE = 'stable' @@ -3831,6 +4149,7 @@ class Sort(str, Enum): Indicates how the returned workspace data will be sorted. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. """ + STABLE = 'stable' @@ -3844,6 +4163,7 @@ class Sort(str, Enum): The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + INTENT = 'intent' UPDATED = 'updated' @@ -3858,6 +4178,7 @@ class Sort(str, Enum): The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3872,6 +4193,7 @@ class Sort(str, Enum): The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3886,6 +4208,7 @@ class Sort(str, Enum): The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + ENTITY = 'entity' UPDATED = 'updated' @@ -3900,6 +4223,7 @@ class Sort(str, Enum): The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + VALUE = 'value' UPDATED = 'updated' @@ -3914,6 +4238,7 @@ class Sort(str, Enum): The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + SYNONYM = 'synonym' UPDATED = 'updated' @@ -3928,6 +4253,7 @@ class Sort(str, Enum): The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + DIALOG_NODE = 'dialog_node' UPDATED = 'updated' @@ -3937,14 +4263,18 @@ class Sort(str, Enum): ############################################################################## -class AgentAvailabilityMessage(): +class AgentAvailabilityMessage: """ AgentAvailabilityMessage. - :attr str message: (optional) The text of the message. + :param str message: (optional) The text of the message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a AgentAvailabilityMessage object. @@ -3956,8 +4286,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -3991,23 +4321,25 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class BulkClassifyOutput(): +class BulkClassifyOutput: """ BulkClassifyOutput. - :attr BulkClassifyUtterance input: (optional) The user input utterance to + :param BulkClassifyUtterance input: (optional) The user input utterance to classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the utterance. """ - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: """ Initialize a BulkClassifyOutput object. @@ -4026,16 +4358,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] return cls(**args) @classmethod @@ -4088,15 +4416,19 @@ def __ne__(self, other: 'BulkClassifyOutput') -> bool: return not self == other -class BulkClassifyResponse(): +class BulkClassifyResponse: """ BulkClassifyResponse. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that + :param List[BulkClassifyOutput] output: (optional) An array of objects that contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: """ Initialize a BulkClassifyResponse object. @@ -4109,10 +4441,8 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(v) for v in _dict.get('output') - ] + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] return cls(**args) @classmethod @@ -4152,14 +4482,17 @@ def __ne__(self, other: 'BulkClassifyResponse') -> bool: return not self == other -class BulkClassifyUtterance(): +class BulkClassifyUtterance: """ The user input utterance to classify. - :attr str text: The text of the input utterance. + :param str text: The text of the input utterance. """ - def __init__(self, text: str) -> None: + def __init__( + self, + text: str, + ) -> None: """ Initialize a BulkClassifyUtterance object. @@ -4171,8 +4504,8 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in BulkClassifyUtterance JSON' @@ -4210,16 +4543,21 @@ def __ne__(self, other: 'BulkClassifyUtterance') -> bool: return not self == other -class CaptureGroup(): +class CaptureGroup: """ A recognized capture group for a pattern-based entity. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a CaptureGroup object. @@ -4234,13 +4572,13 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if (group := _dict.get('group')) is not None: + args['group'] = group else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -4276,18 +4614,21 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other -class ChannelTransferInfo(): +class ChannelTransferInfo: """ Information used by an integration to transfer the conversation to a different channel. - :attr ChannelTransferTarget target: An object specifying target channels + :param ChannelTransferTarget target: An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: """ Initialize a ChannelTransferInfo object. @@ -4302,9 +4643,8 @@ def __init__(self, target: 'ChannelTransferTarget') -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) else: raise ValueError( 'Required property \'target\' not present in ChannelTransferInfo JSON' @@ -4345,17 +4685,21 @@ def __ne__(self, other: 'ChannelTransferInfo') -> bool: return not self == other -class ChannelTransferTarget(): +class ChannelTransferTarget: """ An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: """ Initialize a ChannelTransferTarget object. @@ -4368,9 +4712,8 @@ def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) return cls(**args) @classmethod @@ -4407,14 +4750,18 @@ def __ne__(self, other: 'ChannelTransferTarget') -> bool: return not self == other -class ChannelTransferTargetChat(): +class ChannelTransferTargetChat: """ Information for transferring to the web chat integration. - :attr str url: (optional) The URL of the target web chat. + :param str url: (optional) The URL of the target web chat. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: """ Initialize a ChannelTransferTargetChat object. @@ -4426,8 +4773,8 @@ def __init__(self, *, url: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod @@ -4461,28 +4808,31 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class Context(): +class Context: """ State information for the conversation. To maintain state, include the context from the previous response. - :attr str conversation_id: (optional) The unique identifier of the conversation. - The conversation ID cannot contain any of the following characters: `+` `=` `&&` - `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` `*` `?` `:` `\` `/`. - :attr dict system: (optional) For internal use only. - :attr MessageContextMetadata metadata: (optional) Metadata related to the + :param str conversation_id: (optional) The unique identifier of the + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` + `*` `?` `:` `\` `/`. + :param dict system: (optional) For internal use only. + :param MessageContextMetadata metadata: (optional) Metadata related to the message. """ # The set of defined properties for the class _properties = frozenset(['conversation_id', 'system', 'metadata']) - def __init__(self, - *, - conversation_id: str = None, - system: dict = None, - metadata: 'MessageContextMetadata' = None, - **kwargs) -> None: + def __init__( + self, + *, + conversation_id: Optional[str] = None, + system: Optional[dict] = None, + metadata: Optional['MessageContextMetadata'] = None, + **kwargs, + ) -> None: """ Initialize a Context object. @@ -4505,13 +4855,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} - if 'conversation_id' in _dict: - args['conversation_id'] = _dict.get('conversation_id') - if 'system' in _dict: - args['system'] = _dict.get('system') - if 'metadata' in _dict: - args['metadata'] = MessageContextMetadata.from_dict( - _dict.get('metadata')) + if (conversation_id := _dict.get('conversation_id')) is not None: + args['conversation_id'] = conversation_id + if (system := _dict.get('system')) is not None: + args['system'] = system + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = MessageContextMetadata.from_dict(metadata) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -4580,24 +4929,26 @@ def __ne__(self, other: 'Context') -> bool: return not self == other -class Counterexample(): +class Counterexample: """ Counterexample. - :attr str text: The text of a user input marked as irrelevant input. This string - must conform to the following restrictions: + :param str text: The text of a user input marked as irrelevant input. This + string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Counterexample object. @@ -4614,15 +4965,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Counterexample JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -4660,18 +5011,21 @@ def __ne__(self, other: 'Counterexample') -> bool: return not self == other -class CounterexampleCollection(): +class CounterexampleCollection: """ CounterexampleCollection. - :attr List[Counterexample] counterexamples: An array of objects describing the + :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, counterexamples: List['Counterexample'], - pagination: 'Pagination') -> None: + def __init__( + self, + counterexamples: List['Counterexample'], + pagination: 'Pagination', + ) -> None: """ Initialize a CounterexampleCollection object. @@ -4687,17 +5041,16 @@ def __init__(self, counterexamples: List['Counterexample'], def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(v) - for v in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] else: raise ValueError( 'Required property \'counterexamples\' not present in CounterexampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in CounterexampleCollection JSON' @@ -4747,36 +5100,39 @@ def __ne__(self, other: 'CounterexampleCollection') -> bool: return not self == other -class CreateEntity(): +class CreateEntity: """ CreateEntity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[CreateValue] values: (optional) An array of objects describing the + :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['CreateValue'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['CreateValue']] = None, + ) -> None: """ Initialize a CreateEntity object. @@ -4807,25 +5163,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in CreateEntity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [ - CreateValue.from_dict(v) for v in _dict.get('values') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [CreateValue.from_dict(v) for v in values] return cls(**args) @classmethod @@ -4877,31 +5231,33 @@ def __ne__(self, other: 'CreateEntity') -> bool: return not self == other -class CreateIntent(): +class CreateIntent: """ CreateIntent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a CreateIntent object. @@ -4925,21 +5281,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in CreateIntent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -4987,40 +5341,42 @@ def __ne__(self, other: 'CreateIntent') -> bool: return not self == other -class CreateValue(): +class CreateValue: """ CreateValue. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: (optional) Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: (optional) Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a CreateValue object. @@ -5054,23 +5410,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in CreateValue JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -5119,91 +5475,94 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class DialogNode(): +class DialogNode: """ DialogNode. - :attr str dialog_node: The unique ID of the dialog node. This is an internal + :param str dialog_node: The unique ID of the dialog node. This is an internal identifier used to refer to the dialog node from other dialog nodes and in the diagnostic information included with message responses. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str description: (optional) The description of the dialog node. This + :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str conditions: (optional) The condition that will trigger the dialog + :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str parent: (optional) The unique ID of the parent dialog node. This + :param str parent: (optional) The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent. - :attr str previous_sibling: (optional) The unique ID of the previous sibling + :param str previous_sibling: (optional) The unique ID of the previous sibling dialog node. This property is omitted if the dialog node has no previous sibling. - :attr DialogNodeOutput output: (optional) The output of the dialog node. For + :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr DialogNodeContext context: (optional) The context for the dialog node. - :attr dict metadata: (optional) The metadata for the dialog node. - :attr DialogNodeNextStep next_step: (optional) The next step to execute + :param DialogNodeContext context: (optional) The context for the dialog node. + :param dict metadata: (optional) The metadata for the dialog node. + :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. - :attr str title: (optional) A human-readable name for the dialog node. If the + :param str title: (optional) A human-readable name for the dialog node. If the node is included in disambiguation, this title is used to populate the **label** property of the corresponding suggestion in the `suggestion` response type (unless it is overridden by the **user_label** property). The title is also used to populate the **topic** property in the `connect_to_agent` response type. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str type: (optional) How the dialog node is processed. - :attr str event_name: (optional) How an `event_handler` node is processed. - :attr str variable: (optional) The location in the dialog context where output + :param str type: (optional) How the dialog node is processed. + :param str event_name: (optional) How an `event_handler` node is processed. + :param str variable: (optional) The location in the dialog context where output is stored. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. - :attr str digress_in: (optional) Whether this top-level dialog node can be + :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. - :attr str digress_out: (optional) Whether this dialog node can be returned to + :param str digress_out: (optional) Whether this dialog node can be returned to after a digression. - :attr str digress_out_slots: (optional) Whether the user can digress to + :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. - :attr str user_label: (optional) A label that can be displayed externally to + :param str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. If set, this label is used to identify the node in disambiguation responses (overriding the value of the **title** property). - :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be + :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. - :attr bool disabled: (optional) For internal use only. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param bool disabled: (optional) For internal use only. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - disabled: bool = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + disabled: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a DialogNode object. @@ -5285,57 +5644,55 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node else: raise ValueError( 'Required property \'dialog_node\' not present in DialogNode JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') - if 'parent' in _dict: - args['parent'] = _dict.get('parent') - if 'previous_sibling' in _dict: - args['previous_sibling'] = _dict.get('previous_sibling') - if 'output' in _dict: - args['output'] = DialogNodeOutput.from_dict(_dict.get('output')) - if 'context' in _dict: - args['context'] = DialogNodeContext.from_dict(_dict.get('context')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'next_step' in _dict: - args['next_step'] = DialogNodeNextStep.from_dict( - _dict.get('next_step')) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'event_name' in _dict: - args['event_name'] = _dict.get('event_name') - if 'variable' in _dict: - args['variable'] = _dict.get('variable') - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'digress_in' in _dict: - args['digress_in'] = _dict.get('digress_in') - if 'digress_out' in _dict: - args['digress_out'] = _dict.get('digress_out') - if 'digress_out_slots' in _dict: - args['digress_out_slots'] = _dict.get('digress_out_slots') - if 'user_label' in _dict: - args['user_label'] = _dict.get('user_label') - if 'disambiguation_opt_out' in _dict: - args['disambiguation_opt_out'] = _dict.get('disambiguation_opt_out') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions + if (parent := _dict.get('parent')) is not None: + args['parent'] = parent + if (previous_sibling := _dict.get('previous_sibling')) is not None: + args['previous_sibling'] = previous_sibling + if (output := _dict.get('output')) is not None: + args['output'] = DialogNodeOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = DialogNodeContext.from_dict(context) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (next_step := _dict.get('next_step')) is not None: + args['next_step'] = DialogNodeNextStep.from_dict(next_step) + if (title := _dict.get('title')) is not None: + args['title'] = title + if (type := _dict.get('type')) is not None: + args['type'] = type + if (event_name := _dict.get('event_name')) is not None: + args['event_name'] = event_name + if (variable := _dict.get('variable')) is not None: + args['variable'] = variable + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (digress_in := _dict.get('digress_in')) is not None: + args['digress_in'] = digress_in + if (digress_out := _dict.get('digress_out')) is not None: + args['digress_out'] = digress_out + if (digress_out_slots := _dict.get('digress_out_slots')) is not None: + args['digress_out_slots'] = digress_out_slots + if (user_label := _dict.get('user_label')) is not None: + args['user_label'] = user_label + if (disambiguation_opt_out := + _dict.get('disambiguation_opt_out')) is not None: + args['disambiguation_opt_out'] = disambiguation_opt_out + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -5432,6 +5789,7 @@ class TypeEnum(str, Enum): """ How the dialog node is processed. """ + STANDARD = 'standard' EVENT_HANDLER = 'event_handler' FRAME = 'frame' @@ -5443,6 +5801,7 @@ class EventNameEnum(str, Enum): """ How an `event_handler` node is processed. """ + FOCUS = 'focus' INPUT = 'input' FILLED = 'filled' @@ -5457,6 +5816,7 @@ class DigressInEnum(str, Enum): """ Whether this top-level dialog node can be digressed into. """ + NOT_AVAILABLE = 'not_available' RETURNS = 'returns' DOES_NOT_RETURN = 'does_not_return' @@ -5465,6 +5825,7 @@ class DigressOutEnum(str, Enum): """ Whether this dialog node can be returned to after a digression. """ + ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' ALLOW_ALL_NEVER_RETURN = 'allow_all_never_return' @@ -5473,32 +5834,35 @@ class DigressOutSlotsEnum(str, Enum): """ Whether the user can digress to top-level nodes while filling out slots. """ + NOT_ALLOWED = 'not_allowed' ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' -class DialogNodeAction(): +class DialogNodeAction: """ DialogNodeAction. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result of the action is stored. - :attr str credentials: (optional) The name of the context variable that the + :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeAction object. @@ -5521,24 +5885,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials return cls(**args) @classmethod @@ -5584,6 +5948,7 @@ class TypeEnum(str, Enum): """ The type of action to invoke. """ + CLIENT = 'client' SERVER = 'server' CLOUD_FUNCTION = 'cloud_function' @@ -5591,18 +5956,21 @@ class TypeEnum(str, Enum): WEBHOOK = 'webhook' -class DialogNodeCollection(): +class DialogNodeCollection: """ An array of dialog nodes. - :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog + :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, dialog_nodes: List['DialogNode'], - pagination: 'Pagination') -> None: + def __init__( + self, + dialog_nodes: List['DialogNode'], + pagination: 'Pagination', + ) -> None: """ Initialize a DialogNodeCollection object. @@ -5618,16 +5986,16 @@ def __init__(self, dialog_nodes: List['DialogNode'], def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} - if 'dialog_nodes' in _dict: + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] else: raise ValueError( 'Required property \'dialog_nodes\' not present in DialogNodeCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in DialogNodeCollection JSON' @@ -5676,18 +6044,23 @@ def __ne__(self, other: 'DialogNodeCollection') -> bool: return not self == other -class DialogNodeContext(): +class DialogNodeContext: """ The context for the dialog node. - :attr dict integrations: (optional) Context data intended for specific + :param dict integrations: (optional) Context data intended for specific integrations. """ # The set of defined properties for the class _properties = frozenset(['integrations']) - def __init__(self, *, integrations: dict = None, **kwargs) -> None: + def __init__( + self, + *, + integrations: Optional[dict] = None, + **kwargs, + ) -> None: """ Initialize a DialogNodeContext object. @@ -5703,8 +6076,8 @@ def __init__(self, *, integrations: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': """Initialize a DialogNodeContext object from a json dictionary.""" args = {} - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -5768,11 +6141,11 @@ def __ne__(self, other: 'DialogNodeContext') -> bool: return not self == other -class DialogNodeNextStep(): +class DialogNodeNextStep: """ The next step to execute following this dialog node. - :attr str behavior: What happens after the dialog node completes. The valid + :param str behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` @@ -5793,16 +6166,18 @@ class DialogNodeNextStep(): - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. - :attr str dialog_node: (optional) The unique ID of the dialog node to process + :param str dialog_node: (optional) The unique ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`. - :attr str selector: (optional) Which part of the dialog node to process next. + :param str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, - behavior: str, - *, - dialog_node: str = None, - selector: str = None) -> None: + def __init__( + self, + behavior: str, + *, + dialog_node: Optional[str] = None, + selector: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeNextStep object. @@ -5840,16 +6215,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} - if 'behavior' in _dict: - args['behavior'] = _dict.get('behavior') + if (behavior := _dict.get('behavior')) is not None: + args['behavior'] = behavior else: raise ValueError( 'Required property \'behavior\' not present in DialogNodeNextStep JSON' ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'selector' in _dict: - args['selector'] = _dict.get('selector') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (selector := _dict.get('selector')) is not None: + args['selector'] = selector return cls(**args) @classmethod @@ -5910,6 +6285,7 @@ class BehaviorEnum(str, Enum): If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. """ + GET_USER_INPUT = 'get_user_input' SKIP_USER_INPUT = 'skip_user_input' JUMP_TO = 'jump_to' @@ -5921,36 +6297,39 @@ class SelectorEnum(str, Enum): """ Which part of the dialog node to process next. """ + CONDITION = 'condition' CLIENT = 'client' USER_INPUT = 'user_input' BODY = 'body' -class DialogNodeOutput(): +class DialogNodeOutput: """ The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects + :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. - :attr dict integrations: (optional) Output intended for specific integrations. + :param dict integrations: (optional) Output intended for specific integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). - :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how + :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ # The set of defined properties for the class _properties = frozenset(['generic', 'integrations', 'modifiers']) - def __init__(self, - *, - generic: List['DialogNodeOutputGeneric'] = None, - integrations: dict = None, - modifiers: 'DialogNodeOutputModifiers' = None, - **kwargs) -> None: + def __init__( + self, + *, + generic: Optional[List['DialogNodeOutputGeneric']] = None, + integrations: Optional[dict] = None, + modifiers: Optional['DialogNodeOutputModifiers'] = None, + **kwargs, + ) -> None: """ Initialize a DialogNodeOutput object. @@ -5973,16 +6352,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - DialogNodeOutputGeneric.from_dict(v) - for v in _dict.get('generic') + DialogNodeOutputGeneric.from_dict(v) for v in generic ] - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') - if 'modifiers' in _dict: - args['modifiers'] = DialogNodeOutputModifiers.from_dict( - _dict.get('modifiers')) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + if (modifiers := _dict.get('modifiers')) is not None: + args['modifiers'] = DialogNodeOutputModifiers.from_dict(modifiers) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -6059,14 +6436,18 @@ def __ne__(self, other: 'DialogNodeOutput') -> bool: return not self == other -class DialogNodeOutputConnectToAgentTransferInfo(): +class DialogNodeOutputConnectToAgentTransferInfo: """ Routing or other contextual information to be used by target service desk systems. - :attr dict target: (optional) + :param dict target: (optional) """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: """ Initialize a DialogNodeOutputConnectToAgentTransferInfo object. @@ -6079,8 +6460,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (target := _dict.get('target')) is not None: + args['target'] = target return cls(**args) @classmethod @@ -6116,13 +6497,13 @@ def __ne__(self, return not self == other -class DialogNodeOutputGeneric(): +class DialogNodeOutputGeneric: """ DialogNodeOutputGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a DialogNodeOutputGeneric object. @@ -6149,22 +6530,20 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' + ])) raise Exception(msg) @classmethod @@ -6212,17 +6591,21 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class DialogNodeOutputModifiers(): +class DialogNodeOutputModifiers: """ Options that modify how specified output is handled. - :attr bool overwrite: (optional) Whether values in the output will overwrite + :param bool overwrite: (optional) Whether values in the output will overwrite output values in an array specified by previously executed dialog nodes. If this option is set to `false`, new values will be appended to previously specified values. """ - def __init__(self, *, overwrite: bool = None) -> None: + def __init__( + self, + *, + overwrite: Optional[bool] = None, + ) -> None: """ Initialize a DialogNodeOutputModifiers object. @@ -6237,8 +6620,8 @@ def __init__(self, *, overwrite: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') + if (overwrite := _dict.get('overwrite')) is not None: + args['overwrite'] = overwrite return cls(**args) @classmethod @@ -6272,18 +6655,21 @@ def __ne__(self, other: 'DialogNodeOutputModifiers') -> bool: return not self == other -class DialogNodeOutputOptionsElement(): +class DialogNodeOutputOptionsElement: """ DialogNodeOutputOptionsElement. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -6299,15 +6685,14 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' @@ -6350,28 +6735,30 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: return not self == other -class DialogNodeOutputOptionsElementValue(): +class DialogNodeOutputOptionsElementValue: """ An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be used + :param List[RuntimeIntent] intents: (optional) An array of intents to be used while processing the input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be used + :param List[RuntimeEntity] entities: (optional) An array of entities to be used while processing the user input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -6394,16 +6781,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -6456,16 +6839,20 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodeOutputTextValuesElement(): +class DialogNodeOutputTextValuesElement: """ DialogNodeOutputTextValuesElement. - :attr str text: (optional) The text of a response. This string can include + :param str text: (optional) The text of a response. This string can include newline characters (`\n`), Markdown tagging, or other special characters, if supported by the channel. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputTextValuesElement object. @@ -6479,8 +6866,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -6514,21 +6901,23 @@ def __ne__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: return not self == other -class DialogNodeVisitedDetails(): +class DialogNodeVisitedDetails: """ DialogNodeVisitedDetails. - :attr str dialog_node: (optional) The unique ID of a dialog node that was + :param str dialog_node: (optional) The unique ID of a dialog node that was triggered during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeVisitedDetails object. @@ -6546,12 +6935,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions return cls(**args) @classmethod @@ -6589,32 +6978,34 @@ def __ne__(self, other: 'DialogNodeVisitedDetails') -> bool: return not self == other -class DialogSuggestion(): +class DialogSuggestion: """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **title** or **user_label** property of the corresponding - dialog node. - :attr DialogSuggestionValue value: An object defining the message input, + :param str label: The user-facing label for the disambiguation option. This + label is taken from the **title** or **user_label** property of the + corresponding dialog node. + :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. **Note:** These properties must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr dict output: (optional) The dialog output that will be returned from the + :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **label** property is taken from. The **label** property is populated using the value of the dialog node's **title** or **user_label** property. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None, - dialog_node: str = None) -> None: + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a DialogSuggestion object. @@ -6642,22 +7033,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (output := _dict.get('output')) is not None: + args['output'] = output + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -6700,26 +7091,28 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionValue(): +class DialogSuggestionValue: """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. **Note:** These properties must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent + :param List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent + :param List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogSuggestionValue object. @@ -6738,16 +7131,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -6800,36 +7189,39 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Entity(): +class Entity: """ Entity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Value] values: (optional) An array of objects describing the entity + :param List[Value] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['Value'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['Value']] = None, + ) -> None: """ Initialize a Entity object. @@ -6860,23 +7252,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Entity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [Value.from_dict(v) for v in _dict.get('values')] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] return cls(**args) @classmethod @@ -6928,18 +7320,21 @@ def __ne__(self, other: 'Entity') -> bool: return not self == other -class EntityCollection(): +class EntityCollection: """ An array of objects describing the entities for the workspace. - :attr List[Entity] entities: An array of objects describing the entities defined - for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Entity] entities: An array of objects describing the entities + defined for the workspace. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, entities: List['Entity'], - pagination: 'Pagination') -> None: + def __init__( + self, + entities: List['Entity'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityCollection object. @@ -6955,16 +7350,14 @@ def __init__(self, entities: List['Entity'], def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(v) for v in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in EntityCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityCollection JSON' @@ -7013,17 +7406,22 @@ def __ne__(self, other: 'EntityCollection') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ An object describing a contextual entity mention. - :attr str text: The text of the user input example. - :attr str intent: The name of the intent. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str text: The text of the user input example. + :param str intent: The name of the intent. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, text: str, intent: str, location: List[int]) -> None: + def __init__( + self, + text: str, + intent: str, + location: List[int], + ) -> None: """ Initialize a EntityMention object. @@ -7040,19 +7438,19 @@ def __init__(self, text: str, intent: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in EntityMention JSON') - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in EntityMention JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in EntityMention JSON' @@ -7094,18 +7492,21 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class EntityMentionCollection(): +class EntityMentionCollection: """ EntityMentionCollection. - :attr List[EntityMention] examples: An array of objects describing the entity + :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['EntityMention'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['EntityMention'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityMentionCollection object. @@ -7121,16 +7522,14 @@ def __init__(self, examples: List['EntityMention'], def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - EntityMention.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [EntityMention.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in EntityMentionCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityMentionCollection JSON' @@ -7179,26 +7578,29 @@ def __ne__(self, other: 'EntityMentionCollection') -> bool: return not self == other -class Example(): +class Example: """ Example. - :attr str text: The text of a user input example. This string must conform to + :param str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[Mention] mentions: (optional) An array of contextual entity mentions. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param List[Mention] mentions: (optional) An array of contextual entity + mentions. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - mentions: List['Mention'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + mentions: Optional[List['Mention']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Example object. @@ -7218,19 +7620,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Example JSON') - if 'mentions' in _dict: - args['mentions'] = [ - Mention.from_dict(v) for v in _dict.get('mentions') - ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [Mention.from_dict(v) for v in mentions] + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -7276,18 +7676,21 @@ def __ne__(self, other: 'Example') -> bool: return not self == other -class ExampleCollection(): +class ExampleCollection: """ ExampleCollection. - :attr List[Example] examples: An array of objects describing the examples + :param List[Example] examples: An array of objects describing the examples defined for the intent. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['Example'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['Example'], + pagination: 'Pagination', + ) -> None: """ Initialize a ExampleCollection object. @@ -7303,16 +7706,14 @@ def __init__(self, examples: List['Example'], def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in ExampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ExampleCollection JSON' @@ -7361,31 +7762,33 @@ def __ne__(self, other: 'ExampleCollection') -> bool: return not self == other -class Intent(): +class Intent: """ Intent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a Intent object. @@ -7409,21 +7812,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in Intent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -7471,18 +7872,21 @@ def __ne__(self, other: 'Intent') -> bool: return not self == other -class IntentCollection(): +class IntentCollection: """ IntentCollection. - :attr List[Intent] intents: An array of objects describing the intents defined + :param List[Intent] intents: An array of objects describing the intents defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, intents: List['Intent'], - pagination: 'Pagination') -> None: + def __init__( + self, + intents: List['Intent'], + pagination: 'Pagination', + ) -> None: """ Initialize a IntentCollection object. @@ -7498,16 +7902,14 @@ def __init__(self, intents: List['Intent'], def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(v) for v in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in IntentCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in IntentCollection JSON' @@ -7556,27 +7958,34 @@ def __ne__(self, other: 'IntentCollection') -> bool: return not self == other -class Log(): +class Log: """ Log. - :attr MessageRequest request: A request sent to the workspace, including the + :param MessageRequest request: A request sent to the workspace, including the user input and context. - :attr MessageResponse response: The response sent by the workspace, including + :param MessageResponse response: The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr str log_id: A unique identifier for the logged event. - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the + :param str log_id: A unique identifier for the logged event. + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the message. - :attr str workspace_id: The unique identifier of the workspace where the request - was made. - :attr str language: The language of the workspace where the message request was + :param str workspace_id: The unique identifier of the workspace where the + request was made. + :param str language: The language of the workspace where the message request was made. """ - def __init__(self, request: 'MessageRequest', response: 'MessageResponse', - log_id: str, request_timestamp: str, response_timestamp: str, - workspace_id: str, language: str) -> None: + def __init__( + self, + request: 'MessageRequest', + response: 'MessageResponse', + log_id: str, + request_timestamp: str, + response_timestamp: str, + workspace_id: str, + language: str, + ) -> None: """ Initialize a Log object. @@ -7605,40 +8014,40 @@ def __init__(self, request: 'MessageRequest', response: 'MessageResponse', def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) + if (request := _dict.get('request')) is not None: + args['request'] = MessageRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) + if (response := _dict.get('response')) is not None: + args['response'] = MessageResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp else: raise ValueError( 'Required property \'request_timestamp\' not present in Log JSON' ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp else: raise ValueError( 'Required property \'response_timestamp\' not present in Log JSON' ) - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id else: raise ValueError( 'Required property \'workspace_id\' not present in Log JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Log JSON') @@ -7696,16 +8105,20 @@ def __ne__(self, other: 'Log') -> bool: return not self == other -class LogCollection(): +class LogCollection: """ LogCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: """ Initialize a LogCollection object. @@ -7721,14 +8134,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in LogCollection JSON' @@ -7777,24 +8189,26 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other -class LogMessage(): +class LogMessage: """ Log message details. - :attr str level: The severity of the log message. - :attr str msg: The text of the log message. - :attr str code: A code that indicates the category to which the error message + :param str level: The severity of the log message. + :param str msg: The text of the log message. + :param str code: A code that indicates the category to which the error message belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog + :param LogMessageSource source: (optional) An object that identifies the dialog element that generated the error message. """ - def __init__(self, - level: str, - msg: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + level: str, + msg: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: """ Initialize a LogMessage object. @@ -7814,23 +8228,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') + if (level := _dict.get('level')) is not None: + args['level'] = level else: raise ValueError( 'Required property \'level\' not present in LogMessage JSON') - if 'msg' in _dict: - args['msg'] = _dict.get('msg') + if (msg := _dict.get('msg')) is not None: + args['msg'] = msg else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in LogMessage JSON') - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) return cls(**args) @classmethod @@ -7876,22 +8290,28 @@ class LevelEnum(str, Enum): """ The severity of the log message. """ + INFO = 'info' ERROR = 'error' WARN = 'warn' -class LogMessageSource(): +class LogMessageSource: """ An object that identifies the dialog element that generated the error message. - :attr str type: (optional) A string that indicates the type of dialog element + :param str type: (optional) A string that indicates the type of dialog element that generated the error message. - :attr str dialog_node: (optional) The unique identifier of the dialog node that + :param str dialog_node: (optional) The unique identifier of the dialog node that generated the error message. """ - def __init__(self, *, type: str = None, dialog_node: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a LogMessageSource object. @@ -7907,10 +8327,10 @@ def __init__(self, *, type: str = None, dialog_node: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSource': """Initialize a LogMessageSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -7950,25 +8370,28 @@ class TypeEnum(str, Enum): A string that indicates the type of dialog element that generated the error message. """ + DIALOG_NODE = 'dialog_node' -class LogPagination(): +class LogPagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str next_url: (optional) The URL that will return the next page of + :param str next_url: (optional) The URL that will return the next page of results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a LogPagination object. @@ -7986,12 +8409,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -8029,16 +8452,20 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class Mention(): +class Mention: """ A mention of a contextual entity. - :attr str entity: The name of the entity. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str entity: The name of the entity. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, entity: str, location: List[int]) -> None: + def __init__( + self, + entity: str, + location: List[int], + ) -> None: """ Initialize a Mention object. @@ -8053,13 +8480,13 @@ def __init__(self, entity: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Mention JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in Mention JSON') @@ -8098,14 +8525,14 @@ def __ne__(self, other: 'Mention') -> bool: return not self == other -class MessageContextMetadata(): +class MessageContextMetadata: """ Metadata related to the message. - :attr str deployment: (optional) A label identifying the deployment environment, - used for filtering log data. This string cannot contain carriage return, - newline, or tab characters. - :attr str user_id: (optional) A string value that identifies the user who is + :param str deployment: (optional) A label identifying the deployment + environment, used for filtering log data. This string cannot contain carriage + return, newline, or tab characters. + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8117,7 +8544,12 @@ class MessageContextMetadata(): request, the value specified at the root is used. """ - def __init__(self, *, deployment: str = None, user_id: str = None) -> None: + def __init__( + self, + *, + deployment: Optional[str] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageContextMetadata object. @@ -8142,10 +8574,10 @@ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} - if 'deployment' in _dict: - args['deployment'] = _dict.get('deployment') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (deployment := _dict.get('deployment')) is not None: + args['deployment'] = deployment + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -8181,16 +8613,16 @@ def __ne__(self, other: 'MessageContextMetadata') -> bool: return not self == other -class MessageInput(): +class MessageInput: """ An input object that includes the input text. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr bool spelling_suggestions: (optional) Whether to use spelling correction + :param bool spelling_suggestions: (optional) Whether to use spelling correction when processing the input. This property overrides the value of the **spelling_suggestions** property in the workspace settings. - :attr bool spelling_auto_correct: (optional) Whether to use autocorrection when + :param bool spelling_auto_correct: (optional) Whether to use autocorrection when processing the input. If spelling correction is used and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections @@ -8198,10 +8630,10 @@ class MessageInput(): in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :attr str suggested_text: (optional) Any suggested corrections of the input + :param str suggested_text: (optional) Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. - :attr str original_text: (optional) The original user input text. This property + :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. """ @@ -8211,14 +8643,16 @@ class MessageInput(): 'suggested_text', 'original_text' ]) - def __init__(self, - *, - text: str = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - suggested_text: str = None, - original_text: str = None, - **kwargs) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + suggested_text: Optional[str] = None, + original_text: Optional[str] = None, + **kwargs, + ) -> None: """ Initialize a MessageInput object. @@ -8249,16 +8683,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -8334,27 +8770,27 @@ def __ne__(self, other: 'MessageInput') -> bool: return not self == other -class MessageRequest(): +class MessageRequest: """ A request sent to the workspace, including the user input and context. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: (optional) State information for the conversation. To + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: (optional) State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: (optional) An output object that includes the response + :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8366,16 +8802,18 @@ class MessageRequest(): the value specified at the root is used. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - actions: List['DialogNodeAction'] = None, - user_id: str = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + actions: Optional[List['DialogNodeAction']] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageRequest object. @@ -8420,28 +8858,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -8517,25 +8949,25 @@ def __ne__(self, other: 'MessageRequest') -> bool: return not self == other -class MessageResponse(): +class MessageResponse: """ The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr MessageInput input: An input object that includes the input text. - :attr List[RuntimeIntent] intents: An array of intents recognized in the user + :param MessageInput input: An input object that includes the input text. + :param List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: An array of entities identified in the user + :param List[RuntimeEntity] entities: An array of entities identified in the user input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: State information for the conversation. To maintain + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: An output object that includes the response to the + :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: A string value that identifies the user who is interacting + :param str user_id: A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8547,16 +8979,18 @@ class MessageResponse(): the value specified at the root is used. """ - def __init__(self, - input: 'MessageInput', - intents: List['RuntimeIntent'], - entities: List['RuntimeEntity'], - context: 'Context', - output: 'OutputData', - user_id: str, - *, - alternate_intents: bool = None, - actions: List['DialogNodeAction'] = None) -> None: + def __init__( + self, + input: 'MessageInput', + intents: List['RuntimeIntent'], + entities: List['RuntimeEntity'], + context: 'Context', + output: 'OutputData', + user_id: str, + *, + alternate_intents: Optional[bool] = None, + actions: Optional[List['DialogNodeAction']] = None, + ) -> None: """ Initialize a MessageResponse object. @@ -8595,48 +9029,42 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) else: raise ValueError( 'Required property \'input\' not present in MessageResponse JSON' ) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in MessageResponse JSON' ) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in MessageResponse JSON' ) - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) else: raise ValueError( 'Required property \'context\' not present in MessageResponse JSON' ) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( 'Required property \'user_id\' not present in MessageResponse JSON' @@ -8716,22 +9144,22 @@ def __ne__(self, other: 'MessageResponse') -> bool: return not self == other -class OutputData(): +class OutputData: """ An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :attr List[LogMessage] log_messages: An array of up to 50 messages logged with + :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ @@ -8740,13 +9168,16 @@ class OutputData(): _properties = frozenset( ['nodes_visited', 'nodes_visited_details', 'log_messages', 'generic']) - def __init__(self, - log_messages: List['LogMessage'], - *, - nodes_visited: List[str] = None, - nodes_visited_details: List['DialogNodeVisitedDetails'] = None, - generic: List['RuntimeResponseGeneric'] = None, - **kwargs) -> None: + def __init__( + self, + log_messages: List['LogMessage'], + *, + nodes_visited: Optional[List[str]] = None, + nodes_visited_details: Optional[ + List['DialogNodeVisitedDetails']] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + **kwargs, + ) -> None: """ Initialize a OutputData object. @@ -8776,25 +9207,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = _dict.get('nodes_visited') - if 'nodes_visited_details' in _dict: + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = nodes_visited + if (nodes_visited_details := + _dict.get('nodes_visited_details')) is not None: args['nodes_visited_details'] = [ DialogNodeVisitedDetails.from_dict(v) - for v in _dict.get('nodes_visited_details') + for v in nodes_visited_details ] - if 'log_messages' in _dict: + if (log_messages := _dict.get('log_messages')) is not None: args['log_messages'] = [ - LogMessage.from_dict(v) for v in _dict.get('log_messages') + LogMessage.from_dict(v) for v in log_messages ] else: raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) - for v in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) for v in generic ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -8881,31 +9312,33 @@ def __ne__(self, other: 'OutputData') -> bool: return not self == other -class Pagination(): +class Pagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of results. - :attr int total: (optional) The total number of objects that satisfy the + :param int total: (optional) The total number of objects that satisfy the request. This total includes all results, not just those included in the current page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of results. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - refresh_url: str, - *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a Pagination object. @@ -8932,22 +9365,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( 'Required property \'refresh_url\' not present in Pagination JSON' ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -8991,15 +9424,19 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other -class ResponseGenericChannel(): +class ResponseGenericChannel: """ ResponseGenericChannel. - :attr str channel: (optional) A channel for which the response is intended. + :param str channel: (optional) A channel for which the response is intended. **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: """ Initialize a ResponseGenericChannel object. @@ -9013,8 +9450,8 @@ def __init__(self, *, channel: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod @@ -9052,6 +9489,7 @@ class ChannelEnum(str, Enum): A channel for which the response is intended. **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ + CHAT = 'chat' FACEBOOK = 'facebook' INTERCOM = 'intercom' @@ -9061,44 +9499,46 @@ class ChannelEnum(str, Enum): WHATSAPP = 'whatsapp' -class RuntimeEntity(): +class RuntimeEntity: """ A term from the request that was identified as an entity. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. - :attr str value: The entity value that was recognized in the user input. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param str value: The entity value that was recognized in the user input. + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object + :param RuntimeEntityInterpretation interpretation: (optional) An object containing detailed information about the entity recognized in the user input. For more information about how system entities are interpreted, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of possible alternative values that the user might have intended instead of the value returned in the **value** property. This property is returned only for `@sys-time` and `@sys-date` entities when the user's input is ambiguous. This property is included only if the new system entities are enabled for the workspace. - :attr RuntimeEntityRole role: (optional) An object describing the role played by - a system entity that is specifies the beginning or end of a range recognized in - the user input. This property is included only if the new system entities are + :param RuntimeEntityRole role: (optional) An object describing the role played + by a system entity that is specifies the beginning or end of a range recognized + in the user input. This property is included only if the new system entities are enabled for the workspace. """ - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + ) -> None: """ Initialize a RuntimeEntity object. @@ -9108,7 +9548,7 @@ def __init__(self, offsets that indicate where the detected entity values begin and end in the input text. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -9141,35 +9581,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(v) for v in _dict.get('groups') - ] - if 'interpretation' in _dict: + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) - for v in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) for v in alternatives ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) return cls(**args) @classmethod @@ -9235,24 +9672,29 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other -class RuntimeEntityAlternative(): +class RuntimeEntityAlternative: """ An alternative value for the recognized entity. - :attr str value: (optional) The entity value that was recognized in the user + :param str value: (optional) The entity value that was recognized in the user input. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeEntityAlternative object. :param str value: (optional) The entity value that was recognized in the user input. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. """ self.value = value self.confidence = confidence @@ -9261,10 +9703,10 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9300,108 +9742,110 @@ def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: return not self == other -class RuntimeEntityInterpretation(): +class RuntimeEntityInterpretation: """ RuntimeEntityInterpretation. - :attr str calendar_type: (optional) The calendar used to represent a recognized + :param str calendar_type: (optional) The calendar used to represent a recognized date (for example, `Gregorian`). - :attr str datetime_link: (optional) A unique identifier used to associate a + :param str datetime_link: (optional) A unique identifier used to associate a recognized time and date. If the user input contains a date and time that are mentioned together (for example, `Today at 5`, the same **datetime_link** value is returned for both the `@sys-date` and `@sys-time` entities). - :attr str festival: (optional) A locale-specific holiday name (such as + :param str festival: (optional) A locale-specific holiday name (such as `thanksgiving` or `christmas`). This property is included when a `@sys-date` entity is recognized based on a holiday name in the user input. - :attr str granularity: (optional) The precision or duration of a time range + :param str granularity: (optional) The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - :attr str range_link: (optional) A unique identifier used to associate multiple + :param str range_link: (optional) A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are recognized as a range of values in the user's input (for example, `from July 4 until July 14` or `from 20 to 25`). - :attr str range_modifier: (optional) The word in the user input that indicates + :param str range_modifier: (optional) The word in the user input that indicates that a `sys-date` or `sys-time` entity is part of an implied range where only one date or time is specified (for example, `since` or `until`). - :attr float relative_day: (optional) A recognized mention of a relative day, + :param float relative_day: (optional) A recognized mention of a relative day, represented numerically as an offset from the current date (for example, `-1` for `yesterday` or `10` for `in ten days`). - :attr float relative_month: (optional) A recognized mention of a relative month, - represented numerically as an offset from the current month (for example, `1` - for `next month` or `-3` for `three months ago`). - :attr float relative_week: (optional) A recognized mention of a relative week, + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for example, + `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative week, represented numerically as an offset from the current week (for example, `2` for `in two weeks` or `-1` for `last week). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current + :param float relative_weekend: (optional) A recognized mention of a relative + date range for a weekend, represented numerically as an offset from the current weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :attr float relative_year: (optional) A recognized mention of a relative year, + :param float relative_year: (optional) A recognized mention of a relative year, represented numerically as an offset from the current year (for example, `1` for `next year` or `-5` for `five years ago`). - :attr float specific_day: (optional) A recognized mention of a specific date, + :param float specific_day: (optional) A recognized mention of a specific date, represented numerically as the date within the month (for example, `30` for `June 30`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific + :param str specific_day_of_week: (optional) A recognized mention of a specific day of the week as a lowercase string (for example, `monday`). - :attr float specific_month: (optional) A recognized mention of a specific month, - represented numerically (for example, `7` for `July`). - :attr float specific_quarter: (optional) A recognized mention of a specific + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third quarter`). - :attr float specific_year: (optional) A recognized mention of a specific year + :param float specific_year: (optional) A recognized mention of a specific year (for example, `2016`). - :attr float numeric_value: (optional) A recognized numeric value, represented as - an integer or double. - :attr str subtype: (optional) The type of numeric value recognized in the user + :param float numeric_value: (optional) A recognized numeric value, represented + as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the user input (`integer` or `rational`). - :attr str part_of_day: (optional) A recognized term for a time that was + :param str part_of_day: (optional) A recognized term for a time that was mentioned as a part of the day in the user's input (for example, `morning` or `afternoon`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, + :param float relative_hour: (optional) A recognized mention of a relative hour, represented numerically as an offset from the current hour (for example, `3` for `in three hours` or `-1` for `an hour ago`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time (for example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as + :param float specific_hour: (optional) A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.). - :attr float specific_minute: (optional) A recognized specific minute mentioned + :param float specific_minute: (optional) A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.). - :attr float specific_second: (optional) A recognized specific second mentioned + :param float specific_second: (optional) A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - :attr str timezone: (optional) A recognized time zone mentioned as part of a + :param str timezone: (optional) A recognized time zone mentioned as part of a time value (for example, `EST`). """ - def __init__(self, - *, - calendar_type: str = None, - datetime_link: str = None, - festival: str = None, - granularity: str = None, - range_link: str = None, - range_modifier: str = None, - relative_day: float = None, - relative_month: float = None, - relative_week: float = None, - relative_weekend: float = None, - relative_year: float = None, - specific_day: float = None, - specific_day_of_week: str = None, - specific_month: float = None, - specific_quarter: float = None, - specific_year: float = None, - numeric_value: float = None, - subtype: str = None, - part_of_day: str = None, - relative_hour: float = None, - relative_minute: float = None, - relative_second: float = None, - specific_hour: float = None, - specific_minute: float = None, - specific_second: float = None, - timezone: str = None) -> None: + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityInterpretation object. @@ -9510,58 +9954,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" args = {} - if 'calendar_type' in _dict: - args['calendar_type'] = _dict.get('calendar_type') - if 'datetime_link' in _dict: - args['datetime_link'] = _dict.get('datetime_link') - if 'festival' in _dict: - args['festival'] = _dict.get('festival') - if 'granularity' in _dict: - args['granularity'] = _dict.get('granularity') - if 'range_link' in _dict: - args['range_link'] = _dict.get('range_link') - if 'range_modifier' in _dict: - args['range_modifier'] = _dict.get('range_modifier') - if 'relative_day' in _dict: - args['relative_day'] = _dict.get('relative_day') - if 'relative_month' in _dict: - args['relative_month'] = _dict.get('relative_month') - if 'relative_week' in _dict: - args['relative_week'] = _dict.get('relative_week') - if 'relative_weekend' in _dict: - args['relative_weekend'] = _dict.get('relative_weekend') - if 'relative_year' in _dict: - args['relative_year'] = _dict.get('relative_year') - if 'specific_day' in _dict: - args['specific_day'] = _dict.get('specific_day') - if 'specific_day_of_week' in _dict: - args['specific_day_of_week'] = _dict.get('specific_day_of_week') - if 'specific_month' in _dict: - args['specific_month'] = _dict.get('specific_month') - if 'specific_quarter' in _dict: - args['specific_quarter'] = _dict.get('specific_quarter') - if 'specific_year' in _dict: - args['specific_year'] = _dict.get('specific_year') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') - if 'part_of_day' in _dict: - args['part_of_day'] = _dict.get('part_of_day') - if 'relative_hour' in _dict: - args['relative_hour'] = _dict.get('relative_hour') - if 'relative_minute' in _dict: - args['relative_minute'] = _dict.get('relative_minute') - if 'relative_second' in _dict: - args['relative_second'] = _dict.get('relative_second') - if 'specific_hour' in _dict: - args['specific_hour'] = _dict.get('specific_hour') - if 'specific_minute' in _dict: - args['specific_minute'] = _dict.get('specific_minute') - if 'specific_second' in _dict: - args['specific_second'] = _dict.get('specific_second') - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone return cls(**args) @classmethod @@ -9656,6 +10101,7 @@ class GranularityEnum(str, Enum): The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. """ + DAY = 'day' FORTNIGHT = 'fortnight' HOUR = 'hour' @@ -9669,16 +10115,20 @@ class GranularityEnum(str, Enum): YEAR = 'year' -class RuntimeEntityRole(): +class RuntimeEntityRole: """ An object describing the role played by a system entity that is specifies the beginning or end of a range recognized in the user input. This property is included only if the new system entities are enabled for the workspace. - :attr str type: (optional) The relationship of the entity to the range. + :param str type: (optional) The relationship of the entity to the range. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityRole object. @@ -9690,8 +10140,8 @@ def __init__(self, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -9728,6 +10178,7 @@ class TypeEnum(str, Enum): """ The relationship of the entity to the range. """ + DATE_FROM = 'date_from' DATE_TO = 'date_to' NUMBER_FROM = 'number_from' @@ -9736,25 +10187,29 @@ class TypeEnum(str, Enum): TIME_TO = 'time_to' -class RuntimeIntent(): +class RuntimeIntent: """ An intent identified in the user input. - :attr str intent: The name of the recognized intent. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents confidence in the intent. If you are specifying an intent as part of a request, but you do not have a calculated confidence value, specify `1`. """ - def __init__(self, intent: str, *, confidence: float = None) -> None: + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part - of a request, but you do not have a calculated confidence value, specify - `1`. + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. """ self.intent = intent self.confidence = confidence @@ -9763,14 +10218,14 @@ def __init__(self, intent: str, *, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9806,13 +10261,13 @@ def __ne__(self, other: 'RuntimeIntent') -> bool: return not self == other -class RuntimeResponseGeneric(): +class RuntimeResponseGeneric: """ RuntimeResponseGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -9839,22 +10294,20 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' + ])) raise Exception(msg) @classmethod @@ -9895,15 +10348,19 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class StatusError(): +class StatusError: """ An object describing an error that occurred during processing of an asynchronous operation. - :attr str message: (optional) The text of the error message. + :param str message: (optional) The text of the error message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a StatusError object. @@ -9915,8 +10372,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'StatusError': """Initialize a StatusError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -9950,24 +10407,26 @@ def __ne__(self, other: 'StatusError') -> bool: return not self == other -class Synonym(): +class Synonym: """ Synonym. - :attr str synonym: The text of the synonym. This string must conform to the + :param str synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - synonym: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + synonym: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Synonym object. @@ -9984,15 +10443,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} - if 'synonym' in _dict: - args['synonym'] = _dict.get('synonym') + if (synonym := _dict.get('synonym')) is not None: + args['synonym'] = synonym else: raise ValueError( 'Required property \'synonym\' not present in Synonym JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -10030,17 +10489,20 @@ def __ne__(self, other: 'Synonym') -> bool: return not self == other -class SynonymCollection(): +class SynonymCollection: """ SynonymCollection. - :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Synonym] synonyms: An array of synonyms. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, synonyms: List['Synonym'], - pagination: 'Pagination') -> None: + def __init__( + self, + synonyms: List['Synonym'], + pagination: 'Pagination', + ) -> None: """ Initialize a SynonymCollection object. @@ -10055,16 +10517,14 @@ def __init__(self, synonyms: List['Synonym'], def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} - if 'synonyms' in _dict: - args['synonyms'] = [ - Synonym.from_dict(v) for v in _dict.get('synonyms') - ] + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = [Synonym.from_dict(v) for v in synonyms] else: raise ValueError( 'Required property \'synonyms\' not present in SynonymCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in SynonymCollection JSON' @@ -10113,40 +10573,42 @@ def __ne__(self, other: 'SynonymCollection') -> bool: return not self == other -class Value(): +class Value: """ Value. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - type: str, - *, - metadata: dict = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + type: str, + *, + metadata: Optional[dict] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Value object. @@ -10180,26 +10642,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in Value JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in Value JSON') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -10248,20 +10710,25 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class ValueCollection(): +class ValueCollection: """ ValueCollection. - :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Value] values: An array of entity values. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: + def __init__( + self, + values: List['Value'], + pagination: 'Pagination', + ) -> None: """ Initialize a ValueCollection object. @@ -10276,14 +10743,14 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} - if 'values' in _dict: - args['values'] = [Value.from_dict(v) for v in _dict.get('values')] + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ValueCollection JSON' @@ -10332,25 +10799,27 @@ def __ne__(self, other: 'ValueCollection') -> bool: return not self == other -class Webhook(): +class Webhook: """ A webhook that can be used by dialog nodes to make programmatic calls to an external function. **Note:** Currently, only a single webhook named `main_webhook` is supported. - :attr str url: The URL for the external service or application to which you want - to send HTTP POST requests. - :attr str name: The name of the webhook. Currently, `main_webhook` is the only + :param str url: The URL for the external service or application to which you + want to send HTTP POST requests. + :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :attr List[WebhookHeader] headers_: (optional) An optional array of HTTP headers - to pass with the HTTP request. + :param List[WebhookHeader] headers_: (optional) An optional array of HTTP + headers to pass with the HTTP request. """ - def __init__(self, - url: str, - name: str, - *, - headers_: List['WebhookHeader'] = None) -> None: + def __init__( + self, + url: str, + name: str, + *, + headers_: Optional[List['WebhookHeader']] = None, + ) -> None: """ Initialize a Webhook object. @@ -10369,20 +10838,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Webhook JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Webhook JSON') - if 'headers' in _dict: - args['headers_'] = [ - WebhookHeader.from_dict(v) for v in _dict.get('headers') - ] + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = [WebhookHeader.from_dict(v) for v in headers_] return cls(**args) @classmethod @@ -10426,15 +10893,19 @@ def __ne__(self, other: 'Webhook') -> bool: return not self == other -class WebhookHeader(): +class WebhookHeader: """ A key/value pair defining an HTTP header and a value. - :attr str name: The name of an HTTP header (for example, `Authorization`). - :attr str value: The value of an HTTP header. + :param str name: The name of an HTTP header (for example, `Authorization`). + :param str value: The value of an HTTP header. """ - def __init__(self, name: str, value: str) -> None: + def __init__( + self, + name: str, + value: str, + ) -> None: """ Initialize a WebhookHeader object. @@ -10448,13 +10919,13 @@ def __init__(self, name: str, value: str) -> None: def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in WebhookHeader JSON') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in WebhookHeader JSON') @@ -10493,30 +10964,31 @@ def __ne__(self, other: 'WebhookHeader') -> bool: return not self == other -class Workspace(): +class Workspace: """ Workspace. - :attr str name: The name of the workspace. This string cannot contain carriage + :param str name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the workspace. This string + :param str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the workspace. - :attr str workspace_id: (optional) The workspace ID of the workspace. - :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing + :param str language: The language of the workspace. + :param str workspace_id: (optional) The workspace ID of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :attr List[Counterexample] counterexamples: (optional) An array of objects + :param List[Counterexample] counterexamples: (optional) An array of objects defining input examples that have been marked as irrelevant input. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr dict metadata: (optional) Any metadata related to the workspace. - :attr bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :attr WorkspaceSystemSettings system_settings: (optional) Global settings for + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: Whether training data from the workspace + (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is + not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :attr str status: (optional) The current status of the workspace: + :param str status: (optional) The current status of the workspace: - **Available**: The workspace is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. @@ -10524,38 +10996,40 @@ class Workspace(): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The workspace is training based on new data such as intents or examples. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. - :attr List[Webhook] webhooks: (optional) - :attr List[Intent] intents: (optional) An array of intents. - :attr List[Entity] entities: (optional) An array of objects describing the + :param List[Webhook] webhooks: (optional) + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :attr WorkspaceCounts counts: (optional) An object containing properties that + :param WorkspaceCounts counts: (optional) An object containing properties that indicate how many intents, entities, and dialog nodes are defined in the workspace. This property is included only in responses from the **Export workspace asynchronously** method, and only when the **verbose** query parameter is set to `true`. """ - def __init__(self, - name: str, - language: str, - learning_opt_out: bool, - *, - description: str = None, - workspace_id: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - created: datetime = None, - updated: datetime = None, - metadata: dict = None, - system_settings: 'WorkspaceSystemSettings' = None, - status: str = None, - status_errors: List['StatusError'] = None, - webhooks: List['Webhook'] = None, - intents: List['Intent'] = None, - entities: List['Entity'] = None, - counts: 'WorkspaceCounts' = None) -> None: + def __init__( + self, + name: str, + language: str, + learning_opt_out: bool, + *, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + metadata: Optional[dict] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['Intent']] = None, + entities: Optional[List['Entity']] = None, + counts: Optional['WorkspaceCounts'] = None, + ) -> None: """ Initialize a Workspace object. @@ -10602,64 +11076,57 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Workspace JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Workspace JSON') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'dialog_nodes' in _dict: + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(v) - for v in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'learning_opt_out' in _dict: - args['learning_opt_out'] = _dict.get('learning_opt_out') + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (learning_opt_out := _dict.get('learning_opt_out')) is not None: + args['learning_opt_out'] = learning_opt_out else: raise ValueError( 'Required property \'learning_opt_out\' not present in Workspace JSON' ) - if 'system_settings' in _dict: + if (system_settings := _dict.get('system_settings')) is not None: args['system_settings'] = WorkspaceSystemSettings.from_dict( - _dict.get('system_settings')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + system_settings) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') - ] - if 'webhooks' in _dict: - args['webhooks'] = [ - Webhook.from_dict(v) for v in _dict.get('webhooks') - ] - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(v) for v in _dict.get('entities') + StatusError.from_dict(v) for v in status_errors ] - if 'counts' in _dict: - args['counts'] = WorkspaceCounts.from_dict(_dict.get('counts')) + if (webhooks := _dict.get('webhooks')) is not None: + args['webhooks'] = [Webhook.from_dict(v) for v in webhooks] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] + if (counts := _dict.get('counts')) is not None: + args['counts'] = WorkspaceCounts.from_dict(counts) return cls(**args) @classmethod @@ -10782,6 +11249,7 @@ class StatusEnum(str, Enum): - **Training**: The workspace is training based on new data such as intents or examples. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -10790,18 +11258,21 @@ class StatusEnum(str, Enum): UNAVAILABLE = 'Unavailable' -class WorkspaceCollection(): +class WorkspaceCollection: """ WorkspaceCollection. - :attr List[Workspace] workspaces: An array of objects describing the workspaces + :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, workspaces: List['Workspace'], - pagination: 'Pagination') -> None: + def __init__( + self, + workspaces: List['Workspace'], + pagination: 'Pagination', + ) -> None: """ Initialize a WorkspaceCollection object. @@ -10817,16 +11288,14 @@ def __init__(self, workspaces: List['Workspace'], def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} - if 'workspaces' in _dict: - args['workspaces'] = [ - Workspace.from_dict(v) for v in _dict.get('workspaces') - ] + if (workspaces := _dict.get('workspaces')) is not None: + args['workspaces'] = [Workspace.from_dict(v) for v in workspaces] else: raise ValueError( 'Required property \'workspaces\' not present in WorkspaceCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in WorkspaceCollection JSON' @@ -10875,23 +11344,25 @@ def __ne__(self, other: 'WorkspaceCollection') -> bool: return not self == other -class WorkspaceCounts(): +class WorkspaceCounts: """ An object containing properties that indicate how many intents, entities, and dialog nodes are defined in the workspace. This property is included only in responses from the **Export workspace asynchronously** method, and only when the **verbose** query parameter is set to `true`. - :attr int intent: (optional) The number of intents defined in the workspace. - :attr int entity: (optional) The number of entities defined in the workspace. - :attr int node: (optional) The number of nodes defined in the workspace. + :param int intent: (optional) The number of intents defined in the workspace. + :param int entity: (optional) The number of entities defined in the workspace. + :param int node: (optional) The number of nodes defined in the workspace. """ - def __init__(self, - *, - intent: int = None, - entity: int = None, - node: int = None) -> None: + def __init__( + self, + *, + intent: Optional[int] = None, + entity: Optional[int] = None, + node: Optional[int] = None, + ) -> None: """ Initialize a WorkspaceCounts object. @@ -10909,12 +11380,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceCounts': """Initialize a WorkspaceCounts object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - if 'node' in _dict: - args['node'] = _dict.get('node') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + if (node := _dict.get('node')) is not None: + args['node'] = node return cls(**args) @classmethod @@ -10952,28 +11423,28 @@ def __ne__(self, other: 'WorkspaceCounts') -> bool: return not self == other -class WorkspaceSystemSettings(): +class WorkspaceSystemSettings: """ Global settings for the workspace. - :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings + :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to the Watson Assistant user interface. - :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - :attr dict human_agent_assist: (optional) For internal use only. - :attr bool spelling_suggestions: (optional) Whether spelling correction is + :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) + Workspace settings related to the disambiguation feature. + :param dict human_agent_assist: (optional) For internal use only. + :param bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. - :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled + :param bool spelling_auto_correct: (optional) Whether autocorrection is enabled for the workspace. If spelling correction is enabled and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **original_text** property of the message response. - :attr WorkspaceSystemSettingsSystemEntities system_entities: (optional) + :param WorkspaceSystemSettingsSystemEntities system_entities: (optional) Workspace settings related to the behavior of system entities. - :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings + :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. - :attr WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. """ @@ -10985,17 +11456,20 @@ class WorkspaceSystemSettings(): ]) def __init__( - self, - *, - tooling: 'WorkspaceSystemSettingsTooling' = None, - disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, - human_agent_assist: dict = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None, - nlp: 'WorkspaceSystemSettingsNlp' = None, - **kwargs) -> None: + self, + *, + tooling: Optional['WorkspaceSystemSettingsTooling'] = None, + disambiguation: Optional[ + 'WorkspaceSystemSettingsDisambiguation'] = None, + human_agent_assist: Optional[dict] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + system_entities: Optional[ + 'WorkspaceSystemSettingsSystemEntities'] = None, + off_topic: Optional['WorkspaceSystemSettingsOffTopic'] = None, + nlp: Optional['WorkspaceSystemSettingsNlp'] = None, + **kwargs, + ) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -11037,28 +11511,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - if 'tooling' in _dict: - args['tooling'] = WorkspaceSystemSettingsTooling.from_dict( - _dict.get('tooling')) - if 'disambiguation' in _dict: + if (tooling := _dict.get('tooling')) is not None: + args['tooling'] = WorkspaceSystemSettingsTooling.from_dict(tooling) + if (disambiguation := _dict.get('disambiguation')) is not None: args[ 'disambiguation'] = WorkspaceSystemSettingsDisambiguation.from_dict( - _dict.get('disambiguation')) - if 'human_agent_assist' in _dict: - args['human_agent_assist'] = _dict.get('human_agent_assist') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'system_entities' in _dict: + disambiguation) + if (human_agent_assist := _dict.get('human_agent_assist')) is not None: + args['human_agent_assist'] = human_agent_assist + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (system_entities := _dict.get('system_entities')) is not None: args[ 'system_entities'] = WorkspaceSystemSettingsSystemEntities.from_dict( - _dict.get('system_entities')) - if 'off_topic' in _dict: + system_entities) + if (off_topic := _dict.get('off_topic')) is not None: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( - _dict.get('off_topic')) - if 'nlp' in _dict: - args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(_dict.get('nlp')) + off_topic) + if (nlp := _dict.get('nlp')) is not None: + args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(nlp) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -11156,37 +11631,39 @@ def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: return not self == other -class WorkspaceSystemSettingsDisambiguation(): +class WorkspaceSystemSettingsDisambiguation: """ Workspace settings related to the disambiguation feature. - :attr str prompt: (optional) The text of the introductory prompt that + :param str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. - :attr str none_of_the_above_prompt: (optional) The user-facing label for the + :param str none_of_the_above_prompt: (optional) The user-facing label for the option users can select if none of the suggested options is correct. If no value is specified for this property, this option does not appear. - :attr bool enabled: (optional) Whether the disambiguation feature is enabled for - the workspace. - :attr str sensitivity: (optional) The sensitivity of the disambiguation feature + :param bool enabled: (optional) Whether the disambiguation feature is enabled + for the workspace. + :param str sensitivity: (optional) The sensitivity of the disambiguation feature to intent detection uncertainty. Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. - :attr bool randomize: (optional) Whether the order in which disambiguation + :param bool randomize: (optional) Whether the order in which disambiguation suggestions are presented should be randomized (but still influenced by relative confidence). - :attr int max_suggestions: (optional) The maximum number of disambigation + :param int max_suggestions: (optional) The maximum number of disambigation suggestions that can be included in a `suggestion` response. - :attr str suggestion_text_policy: (optional) For internal use only. + :param str suggestion_text_policy: (optional) For internal use only. """ - def __init__(self, - *, - prompt: str = None, - none_of_the_above_prompt: str = None, - enabled: bool = None, - sensitivity: str = None, - randomize: bool = None, - max_suggestions: int = None, - suggestion_text_policy: str = None) -> None: + def __init__( + self, + *, + prompt: Optional[str] = None, + none_of_the_above_prompt: Optional[str] = None, + enabled: Optional[bool] = None, + sensitivity: Optional[str] = None, + randomize: Optional[bool] = None, + max_suggestions: Optional[int] = None, + suggestion_text_policy: Optional[str] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -11219,21 +11696,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') - if 'none_of_the_above_prompt' in _dict: - args['none_of_the_above_prompt'] = _dict.get( - 'none_of_the_above_prompt') - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'sensitivity' in _dict: - args['sensitivity'] = _dict.get('sensitivity') - if 'randomize' in _dict: - args['randomize'] = _dict.get('randomize') - if 'max_suggestions' in _dict: - args['max_suggestions'] = _dict.get('max_suggestions') - if 'suggestion_text_policy' in _dict: - args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt + if (none_of_the_above_prompt := + _dict.get('none_of_the_above_prompt')) is not None: + args['none_of_the_above_prompt'] = none_of_the_above_prompt + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (sensitivity := _dict.get('sensitivity')) is not None: + args['sensitivity'] = sensitivity + if (randomize := _dict.get('randomize')) is not None: + args['randomize'] = randomize + if (max_suggestions := _dict.get('max_suggestions')) is not None: + args['max_suggestions'] = max_suggestions + if (suggestion_text_policy := + _dict.get('suggestion_text_policy')) is not None: + args['suggestion_text_policy'] = suggestion_text_policy return cls(**args) @classmethod @@ -11287,6 +11765,7 @@ class SensitivityEnum(str, Enum): Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. """ + AUTO = 'auto' HIGH = 'high' MEDIUM_HIGH = 'medium_high' @@ -11295,12 +11774,12 @@ class SensitivityEnum(str, Enum): LOW = 'low' -class WorkspaceSystemSettingsNlp(): +class WorkspaceSystemSettingsNlp: """ Workspace settings related to the version of the training algorithms currently used by the skill. - :attr str model: (optional) The policy the skill follows for selecting the + :param str model: (optional) The policy the skill follows for selecting the algorithm version to use. For more information, see the [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). On IBM Cloud, you can specify `latest`, `previous`, or `beta`. @@ -11308,7 +11787,11 @@ class WorkspaceSystemSettingsNlp(): version you want to use, in `YYYY-MM-DD` format. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsNlp object. @@ -11325,8 +11808,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsNlp': """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -11360,15 +11843,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: return not self == other -class WorkspaceSystemSettingsOffTopic(): +class WorkspaceSystemSettingsOffTopic: """ Workspace settings related to detection of irrelevant input. - :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled - for the workspace. + :param bool enabled: (optional) Whether enhanced irrelevance detection is + enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsOffTopic object. @@ -11381,8 +11868,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -11416,15 +11903,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: return not self == other -class WorkspaceSystemSettingsSystemEntities(): +class WorkspaceSystemSettingsSystemEntities: """ Workspace settings related to the behavior of system entities. - :attr bool enabled: (optional) Whether the new system entities are enabled for + :param bool enabled: (optional) Whether the new system entities are enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsSystemEntities object. @@ -11437,8 +11928,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -11472,15 +11963,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: return not self == other -class WorkspaceSystemSettingsTooling(): +class WorkspaceSystemSettingsTooling: """ Workspace settings related to the Watson Assistant user interface. - :attr bool store_generic_responses: (optional) Whether the dialog JSON editor + :param bool store_generic_responses: (optional) Whether the dialog JSON editor displays text responses within the `output.generic` object. """ - def __init__(self, *, store_generic_responses: bool = None) -> None: + def __init__( + self, + *, + store_generic_responses: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsTooling object. @@ -11493,9 +11988,9 @@ def __init__(self, *, store_generic_responses: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - if 'store_generic_responses' in _dict: - args['store_generic_responses'] = _dict.get( - 'store_generic_responses') + if (store_generic_responses := + _dict.get('store_generic_responses')) is not None: + args['store_generic_responses'] = store_generic_responses return cls(**args) @classmethod @@ -11535,30 +12030,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. @@ -11592,31 +12089,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11678,24 +12174,26 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object. @@ -11723,29 +12221,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11807,32 +12303,34 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) An optional message to be sent to + :param str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object. @@ -11867,28 +12365,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'channels' in _dict: + transfer_info) + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11962,28 +12460,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object. @@ -12015,28 +12515,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12096,26 +12595,28 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the image. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. @@ -12145,29 +12646,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -12226,28 +12726,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str title: An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str preference: (optional) The preferred type of control to display, if + :param str preference: (optional) The preferred type of control to display, if supported by the channel. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. You can include up to 20 options. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. @@ -12279,35 +12781,33 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12371,6 +12871,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display, if supported by the channel. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -12380,22 +12881,24 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( """ DialogNodeOutputGenericDialogNodeOutputResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. The valid values are from 0 + :param int time: How long to pause, in milliseconds. The valid values are from 0 to 10000. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object. @@ -12421,24 +12924,23 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12494,33 +12996,35 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is used only by the v2 runtime API. - :attr str query: The text of the search query. This can be either a + :param str query: The text of the search query. This can be either a natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). - :attr str query_type: The type of the search query. - :attr str filter: (optional) An optional filter that narrows the set of + :param str query_type: The type of the search query. + :param str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). - :attr str discovery_version: (optional) The version of the Discovery service API - to use for the query. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str discovery_version: (optional) The version of the Discovery service + API to use for the query. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - query: str, - query_type: str, - *, - filter: str = None, - discovery_version: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + query: str, + query_type: str, + *, + filter: Optional[str] = None, + discovery_version: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object. @@ -12558,32 +13062,31 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query' in _dict: - args['query'] = _dict.get('query') + if (query := _dict.get('query')) is not None: + args['query'] = query else: raise ValueError( 'Required property \'query\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query_type' in _dict: - args['query_type'] = _dict.get('query_type') + if (query_type := _dict.get('query_type')) is not None: + args['query_type'] = query_type else: raise ValueError( 'Required property \'query_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'discovery_version' in _dict: - args['discovery_version'] = _dict.get('discovery_version') - if 'channels' in _dict: + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (discovery_version := _dict.get('discovery_version')) is not None: + args['discovery_version'] = discovery_version + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12644,6 +13147,7 @@ class QueryTypeEnum(str, Enum): """ The type of the search query. """ + NATURAL_LANGUAGE = 'natural_language' DISCOVERY_QUERY_LANGUAGE = 'discovery_query_language' @@ -12653,25 +13157,27 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr List[DialogNodeOutputTextValuesElement] values: A list of one or more + :param List[DialogNodeOutputTextValuesElement] values: A list of one or more objects defining text responses. - :attr str selection_policy: (optional) How a response is selected from the list, - if more than one response is specified. - :attr str delimiter: (optional) The delimiter to use as a separator between + :param str selection_policy: (optional) How a response is selected from the + list, if more than one response is specified. + :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - values: List['DialogNodeOutputTextValuesElement'], - *, - selection_policy: str = None, - delimiter: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + values: List['DialogNodeOutputTextValuesElement'], + *, + selection_policy: Optional[str] = None, + delimiter: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object. @@ -12700,29 +13206,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'values' in _dict: + if (values := _dict.get('values')) is not None: args['values'] = [ - DialogNodeOutputTextValuesElement.from_dict(v) - for v in _dict.get('values') + DialogNodeOutputTextValuesElement.from_dict(v) for v in values ] else: raise ValueError( 'Required property \'values\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'selection_policy' in _dict: - args['selection_policy'] = _dict.get('selection_policy') - if 'delimiter' in _dict: - args['delimiter'] = _dict.get('delimiter') - if 'channels' in _dict: + if (selection_policy := _dict.get('selection_policy')) is not None: + args['selection_policy'] = selection_policy + if (delimiter := _dict.get('delimiter')) is not None: + args['delimiter'] = delimiter + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12785,6 +13289,7 @@ class SelectionPolicyEnum(str, Enum): """ How a response is selected from the list, if more than one response is specified. """ + SEQUENTIAL = 'sequential' RANDOM = 'random' MULTILINE = 'multiline' @@ -12795,20 +13300,22 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. The total size of this object cannot exceed 5000 bytes. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object. @@ -12832,22 +13339,21 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12903,30 +13409,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the video. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. @@ -12960,31 +13468,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13045,30 +13552,32 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -13103,31 +13612,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13187,26 +13695,28 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( """ RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. @@ -13236,29 +13746,27 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13318,42 +13826,44 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( """ RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human + :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr str topic: (optional) A label identifying the topic of the conversation, + :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **title** property. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - dialog_node: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + dialog_node: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -13398,32 +13908,32 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'channels' in _dict: + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13498,28 +14008,30 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str description: (optional) The description to show with the response. + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -13552,28 +14064,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13632,28 +14143,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the image. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -13686,29 +14199,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13764,27 +14276,29 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -13817,35 +14331,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13909,6 +14421,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -13917,23 +14430,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -13960,24 +14475,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14031,23 +14545,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -14075,30 +14591,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14159,20 +14674,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -14196,22 +14713,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14263,21 +14779,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -14302,22 +14820,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14370,30 +14887,32 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -14428,31 +14947,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 1875780d..764f567f 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,13 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ -The IBM Watson™ Assistant service combines machine learning, natural language +The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and receive a response. +You need a paid Plus plan or higher to use the watsonx Assistant v2 API. API Version: 2.0 See: https://cloud.ibm.com/docs/assistant @@ -28,7 +29,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional import json import sys @@ -60,7 +61,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-11-27`. + Specify dates in YYYY-MM-DD format. The current version is `2023-06-15`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -81,17 +82,18 @@ def __init__( # Assistants ######################### - def create_assistant(self, - *, - language: str = None, - name: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_assistant( + self, + *, + language: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create an assistant. Create a new assistant. - This method is available only with Enterprise plans. :param str language: (optional) The language of the assistant. :param str name: (optional) The name of the assistant. This string cannot @@ -104,9 +106,11 @@ def create_assistant(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_assistant') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_assistant', + ) headers.update(sdk_headers) params = { @@ -128,28 +132,31 @@ def create_assistant(self, headers['Accept'] = 'application/json' url = '/v2/assistants' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_assistants(self, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_assistants( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List assistants. - List the assistants associated with a Watson Assistant service instance. - This method is available only with Enterprise plans. + List the assistants associated with a watsonx Assistant service instance. :param int page_limit: (optional) The number of records to return in each page of results. @@ -170,9 +177,11 @@ def list_assistants(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_assistants') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_assistants', + ) headers.update(sdk_headers) params = { @@ -190,20 +199,25 @@ def list_assistants(self, headers['Accept'] = 'application/json' url = '/v2/assistants' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: + def delete_assistant( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete assistant. Delete an assistant. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -211,7 +225,7 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -225,9 +239,11 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_assistant') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_assistant', + ) headers.update(sdk_headers) params = { @@ -243,10 +259,12 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -255,11 +273,13 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: # Sessions ######################### - def create_session(self, - assistant_id: str, - *, - analytics: 'RequestAnalytics' = None, - **kwargs) -> DetailedResponse: + def create_session( + self, + assistant_id: str, + *, + analytics: Optional['RequestAnalytics'] = None, + **kwargs, + ) -> DetailedResponse: """ Create a session. @@ -267,7 +287,7 @@ def create_session(self, responses. It also maintains the state of the conversation. A session persists until it is deleted, or until it times out because of inactivity. (For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings).). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -275,7 +295,7 @@ def create_session(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -294,9 +314,11 @@ def create_session(self, if analytics is not None: analytics = convert_model(analytics) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_session', + ) headers.update(sdk_headers) params = { @@ -319,17 +341,23 @@ def create_session(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_session(self, assistant_id: str, session_id: str, - **kwargs) -> DetailedResponse: + def delete_session( + self, + assistant_id: str, + session_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete session. @@ -343,7 +371,7 @@ def delete_session(self, assistant_id: str, session_id: str, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -360,9 +388,11 @@ def delete_session(self, assistant_id: str, session_id: str, if not session_id: raise ValueError('session_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_session', + ) headers.update(sdk_headers) params = { @@ -379,10 +409,12 @@ def delete_session(self, assistant_id: str, session_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -391,19 +423,21 @@ def delete_session(self, assistant_id: str, session_id: str, # Message ######################### - def message(self, - assistant_id: str, - session_id: str, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message( + self, + assistant_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateful). Send user input to an assistant and receive a response, with conversation state - (including context data) stored by Watson Assistant for the duration of the + (including context data) stored by watsonx Assistant for the duration of the session. :param str assistant_id: The assistant ID or the environment ID of the @@ -412,7 +446,7 @@ def message(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -439,7 +473,7 @@ def message(self, value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object + :rtype: DetailedResponse with `dict` result representing a `StatefulMessageResponse` object """ if not assistant_id: @@ -451,9 +485,11 @@ def message(self, if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message', + ) headers.update(sdk_headers) params = { @@ -479,22 +515,26 @@ def message(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def message_stateless(self, - assistant_id: str, - *, - input: 'MessageInputStateless' = None, - context: 'MessageContextStateless' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message_stateless( + self, + assistant_id: str, + *, + input: Optional['StatelessMessageInput'] = None, + context: Optional['StatelessMessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateless). @@ -507,15 +547,15 @@ def message_stateless(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param MessageInputStateless input: (optional) An input object that + :param StatelessMessageInput input: (optional) An input object that includes the input text. - :param MessageContextStateless context: (optional) Context data for the + :param StatelessMessageContext context: (optional) Context data for the conversation. You can use this property to set or modify context variables, which can also be accessed by dialog nodes. The context is not stored by the assistant. To maintain session state, include the context from the @@ -534,7 +574,7 @@ def message_stateless(self, message request, the value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object + :rtype: DetailedResponse with `dict` result representing a `StatelessMessageResponse` object """ if not assistant_id: @@ -544,9 +584,11 @@ def message_stateless(self, if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message_stateless') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stateless', + ) headers.update(sdk_headers) params = { @@ -571,11 +613,13 @@ def message_stateless(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -584,8 +628,12 @@ def message_stateless(self, # Bulk classify ######################### - def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], - **kwargs) -> DetailedResponse: + def bulk_classify( + self, + skill_id: str, + input: List['BulkClassifyUtterance'], + **kwargs, + ) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -596,7 +644,7 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], This method is available only with Enterprise with Data Isolation plans. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param List[BulkClassifyUtterance] input: An array of input utterances to classify. @@ -611,9 +659,11 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], raise ValueError('input must be provided') input = [convert_model(x) for x in input] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify', + ) headers.update(sdk_headers) params = { @@ -637,11 +687,13 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -650,20 +702,21 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], # Logs ######################### - def list_logs(self, - assistant_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_logs( + self, + assistant_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events for an assistant. List the events from the log of an assistant. - This method requires Manager access, and is available only with Plus and - Enterprise plans. + This method requires Manager access. **Note:** If you use the **cursor** parameter to retrieve results one page at a time, subsequent requests must be no more than 5 minutes apart. Any returned value for the **cursor** parameter becomes invalid after 5 minutes. For more information @@ -675,7 +728,7 @@ def list_logs(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -689,6 +742,8 @@ def list_logs(self, [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param int page_limit: (optional) The number of records to return in each page of results. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -699,9 +754,11 @@ def list_logs(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -721,10 +778,12 @@ def list_logs(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -733,7 +792,11 @@ def list_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -746,7 +809,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: **Note:** This operation is intended only for deleting data associated with a single specific customer, not for deleting data associated with multiple customers or for any other purpose. For more information, see [Labeling and deleting data in - Watson + watsonx Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). :param str customer_id: The customer ID for which all data is to be @@ -759,9 +822,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -775,10 +840,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -787,20 +854,21 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: # Environments ######################### - def list_environments(self, - assistant_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_environments( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List environments. List the environments associated with an assistant. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -808,7 +876,7 @@ def list_environments(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -835,9 +903,11 @@ def list_environments(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_environments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_environments', + ) headers.update(sdk_headers) params = { @@ -859,26 +929,29 @@ def list_environments(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_environment(self, - assistant_id: str, - environment_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_environment( + self, + assistant_id: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get environment. Get information about an environment. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -886,14 +959,14 @@ def get_environment(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str environment_id: Unique identifier of the environment. To find - the environment ID in the Watson Assistant user interface, open the + the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the API does not support creating environments. :param bool include_audit: (optional) Whether to include the audit @@ -908,9 +981,11 @@ def get_environment(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_environment', + ) headers.update(sdk_headers) params = { @@ -928,30 +1003,34 @@ def get_environment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_environment(self, - assistant_id: str, - environment_id: str, - *, - name: str = None, - description: str = None, - session_timeout: int = None, - skill_references: List['EnvironmentSkill'] = None, - **kwargs) -> DetailedResponse: + def update_environment( + self, + assistant_id: str, + environment_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + orchestration: Optional['BaseEnvironmentOrchestration'] = None, + session_timeout: Optional[int] = None, + skill_references: Optional[List['EnvironmentSkill']] = None, + **kwargs, + ) -> DetailedResponse: """ Update environment. Update an environment with new or modified data. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -959,18 +1038,20 @@ def update_environment(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str environment_id: Unique identifier of the environment. To find - the environment ID in the Watson Assistant user interface, open the + the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the API does not support creating environments. :param str name: (optional) The name of the environment. :param str description: (optional) The description of the environment. + :param BaseEnvironmentOrchestration orchestration: (optional) The search + skill orchestration settings for the environment. :param int session_timeout: (optional) The session inactivity timeout setting for the environment (in seconds). :param List[EnvironmentSkill] skill_references: (optional) An array of @@ -985,12 +1066,16 @@ def update_environment(self, raise ValueError('assistant_id must be provided') if not environment_id: raise ValueError('environment_id must be provided') + if orchestration is not None: + orchestration = convert_model(orchestration) if skill_references is not None: skill_references = [convert_model(x) for x in skill_references] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_environment', + ) headers.update(sdk_headers) params = { @@ -1000,6 +1085,7 @@ def update_environment(self, data = { 'name': name, 'description': description, + 'orchestration': orchestration, 'session_timeout': session_timeout, 'skill_references': skill_references, } @@ -1017,11 +1103,13 @@ def update_environment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -1030,18 +1118,19 @@ def update_environment(self, # Releases ######################### - def create_release(self, - assistant_id: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def create_release( + self, + assistant_id: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create release. Create a new release using the current content of the dialog and action skills in - the draft environment. (In the Watson Assistant user interface, a release is - called a *version*.) - This method is available only with Enterprise plans. + the draft environment. (In the watsonx Assistant user interface, a release is + called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1049,7 +1138,7 @@ def create_release(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1064,9 +1153,11 @@ def create_release(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release', + ) headers.update(sdk_headers) params = { @@ -1089,30 +1180,33 @@ def create_release(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_releases(self, - assistant_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_releases( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List releases. - List the releases associated with an assistant. (In the Watson Assistant user - interface, a release is called a *version*.) - This method is available only with Enterprise plans. + List the releases associated with an assistant. (In the watsonx Assistant user + interface, a release is called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1120,7 +1214,7 @@ def list_releases(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1147,9 +1241,11 @@ def list_releases(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_releases') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_releases', + ) headers.update(sdk_headers) params = { @@ -1170,20 +1266,24 @@ def list_releases(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_release(self, - assistant_id: str, - release: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_release( + self, + assistant_id: str, + release: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get release. @@ -1192,7 +1292,6 @@ def get_release(self, publishing is still in progress, you can continue to poll by calling the same request again and checking the value of the **status** property. When processing has completed, the request returns the release data. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1200,7 +1299,7 @@ def get_release(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1219,9 +1318,11 @@ def get_release(self, if not release: raise ValueError('release must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release', + ) headers.update(sdk_headers) params = { @@ -1239,22 +1340,27 @@ def get_release(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_release(self, assistant_id: str, release: str, - **kwargs) -> DetailedResponse: + def delete_release( + self, + assistant_id: str, + release: str, + **kwargs, + ) -> DetailedResponse: """ Delete release. - Delete a release. (In the Watson Assistant user interface, a release is called a - *version*.) - This method is available only with Enterprise plans. + Delete a release. (In the watsonx Assistant user interface, a release is called a + *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1262,7 +1368,7 @@ def delete_release(self, assistant_id: str, release: str, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1279,9 +1385,11 @@ def delete_release(self, assistant_id: str, release: str, if not release: raise ValueError('release must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_release', + ) headers.update(sdk_headers) params = { @@ -1298,27 +1406,30 @@ def delete_release(self, assistant_id: str, release: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def deploy_release(self, - assistant_id: str, - release: str, - environment_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def deploy_release( + self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Deploy release. Update the environment with the content of the release. All snapshots saved as part of the release become active in the environment. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1326,7 +1437,7 @@ def deploy_release(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1349,9 +1460,11 @@ def deploy_release(self, if environment_id is None: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='deploy_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release', + ) headers.update(sdk_headers) params = { @@ -1376,11 +1489,13 @@ def deploy_release(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -1389,13 +1504,16 @@ def deploy_release(self, # Skills ######################### - def get_skill(self, assistant_id: str, skill_id: str, - **kwargs) -> DetailedResponse: + def get_skill( + self, + assistant_id: str, + skill_id: str, + **kwargs, + ) -> DetailedResponse: """ Get skill. Get information about a skill. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1403,14 +1521,14 @@ def get_skill(self, assistant_id: str, skill_id: str, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1422,9 +1540,11 @@ def get_skill(self, assistant_id: str, skill_id: str, if not skill_id: raise ValueError('skill_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_skill') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_skill', + ) headers.update(sdk_headers) params = { @@ -1441,24 +1561,28 @@ def get_skill(self, assistant_id: str, skill_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_skill(self, - assistant_id: str, - skill_id: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - dialog_settings: dict = None, - search_settings: 'SearchSettings' = None, - **kwargs) -> DetailedResponse: + def update_skill( + self, + assistant_id: str, + skill_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + dialog_settings: Optional[dict] = None, + search_settings: Optional['SearchSettings'] = None, + **kwargs, + ) -> DetailedResponse: """ Update skill. @@ -1466,7 +1590,6 @@ def update_skill(self, **Note:** The update is performed asynchronously; you can see the status of the update by calling the **Get skill** method and checking the value of the **status** property. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1474,14 +1597,14 @@ def update_skill(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. @@ -1492,6 +1615,8 @@ def update_skill(self, :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Skill` object @@ -1504,9 +1629,11 @@ def update_skill(self, if search_settings is not None: search_settings = convert_model(search_settings) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_skill') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill', + ) headers.update(sdk_headers) params = { @@ -1534,20 +1661,24 @@ def update_skill(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def export_skills(self, - assistant_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def export_skills( + self, + assistant_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Export skills. @@ -1564,7 +1695,6 @@ def export_skills(self, failure. When processing has completed, the request returns the exported JSON data. Remember that the usual rate limits apply. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1572,7 +1702,7 @@ def export_skills(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1588,9 +1718,11 @@ def export_skills(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='export_skills') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills', + ) headers.update(sdk_headers) params = { @@ -1608,21 +1740,25 @@ def export_skills(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_export'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def import_skills(self, - assistant_id: str, - assistant_skills: List['SkillImport'], - assistant_state: 'AssistantState', - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def import_skills( + self, + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Import skills. @@ -1635,7 +1771,6 @@ def import_skills(self, skills belonging to the assistant are not available until processing completes. To check the status of the asynchronous import operation, use the **Get status of skills import** method. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1643,7 +1778,7 @@ def import_skills(self, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1670,9 +1805,11 @@ def import_skills(self, assistant_skills = [convert_model(x) for x in assistant_skills] assistant_state = convert_model(assistant_state) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='import_skills') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills', + ) headers.update(sdk_headers) params = { @@ -1698,23 +1835,27 @@ def import_skills(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_import'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def import_skills_status(self, assistant_id: str, - **kwargs) -> DetailedResponse: + def import_skills_status( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: """ Get status of skills import. Retrieve the status of an asynchronous import operation previously initiated by using the **Import skills** method. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1722,7 +1863,7 @@ def import_skills_status(self, assistant_id: str, - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1736,9 +1877,11 @@ def import_skills_status(self, assistant_id: str, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='import_skills_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status', + ) headers.update(sdk_headers) params = { @@ -1755,10 +1898,12 @@ def import_skills_status(self, assistant_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_import/status'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1774,6 +1919,7 @@ class Sort(str, Enum): The attribute by which returned assistants will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1788,6 +1934,7 @@ class Sort(str, Enum): The attribute by which returned environments will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1802,6 +1949,7 @@ class Sort(str, Enum): The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1811,14 +1959,18 @@ class Sort(str, Enum): ############################################################################## -class AgentAvailabilityMessage(): +class AgentAvailabilityMessage: """ AgentAvailabilityMessage. - :attr str message: (optional) The text of the message. + :param str message: (optional) The text of the message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a AgentAvailabilityMessage object. @@ -1830,8 +1982,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -1865,18 +2017,21 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class AssistantCollection(): +class AssistantCollection: """ AssistantCollection. - :attr List[AssistantData] assistants: An array of objects describing the + :param List[AssistantData] assistants: An array of objects describing the assistants associated with the instance. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, assistants: List['AssistantData'], - pagination: 'Pagination') -> None: + def __init__( + self, + assistants: List['AssistantData'], + pagination: 'Pagination', + ) -> None: """ Initialize a AssistantCollection object. @@ -1892,16 +2047,16 @@ def __init__(self, assistants: List['AssistantData'], def from_dict(cls, _dict: Dict) -> 'AssistantCollection': """Initialize a AssistantCollection object from a json dictionary.""" args = {} - if 'assistants' in _dict: + if (assistants := _dict.get('assistants')) is not None: args['assistants'] = [ - AssistantData.from_dict(v) for v in _dict.get('assistants') + AssistantData.from_dict(v) for v in assistants ] else: raise ValueError( 'Required property \'assistants\' not present in AssistantCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in AssistantCollection JSON' @@ -1950,31 +2105,31 @@ def __ne__(self, other: 'AssistantCollection') -> bool: return not self == other -class AssistantData(): +class AssistantData: """ AssistantData. - :attr str assistant_id: (optional) The unique identifier of the assistant. - :attr str name: (optional) The name of the assistant. This string cannot contain - carriage return, newline, or tab characters. - :attr str description: (optional) The description of the assistant. This string + :param str assistant_id: (optional) The unique identifier of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This string cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the assistant. - :attr List[AssistantSkill] assistant_skills: (optional) An array of skill + :param str language: The language of the assistant. + :param List[AssistantSkill] assistant_skills: (optional) An array of skill references identifying the skills associated with the assistant. - :attr List[EnvironmentReference] assistant_environments: (optional) An array of + :param List[EnvironmentReference] assistant_environments: (optional) An array of objects describing the environments defined for the assistant. """ def __init__( - self, - language: str, - *, - assistant_id: str = None, - name: str = None, - description: str = None, - assistant_skills: List['AssistantSkill'] = None, - assistant_environments: List['EnvironmentReference'] = None + self, + language: str, + *, + assistant_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_skills: Optional[List['AssistantSkill']] = None, + assistant_environments: Optional[List['EnvironmentReference']] = None, ) -> None: """ Initialize a AssistantData object. @@ -1996,27 +2151,27 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'AssistantData': """Initialize a AssistantData object from a json dictionary.""" args = {} - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in AssistantData JSON' ) - if 'assistant_skills' in _dict: + if (assistant_skills := _dict.get('assistant_skills')) is not None: args['assistant_skills'] = [ - AssistantSkill.from_dict(v) - for v in _dict.get('assistant_skills') + AssistantSkill.from_dict(v) for v in assistant_skills ] - if 'assistant_environments' in _dict: + if (assistant_environments := + _dict.get('assistant_environments')) is not None: args['assistant_environments'] = [ EnvironmentReference.from_dict(v) - for v in _dict.get('assistant_environments') + for v in assistant_environments ] return cls(**args) @@ -2076,15 +2231,20 @@ def __ne__(self, other: 'AssistantData') -> bool: return not self == other -class AssistantSkill(): +class AssistantSkill: """ AssistantSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ - def __init__(self, skill_id: str, *, type: str = None) -> None: + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a AssistantSkill object. @@ -2098,14 +2258,14 @@ def __init__(self, skill_id: str, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AssistantSkill': """Initialize a AssistantSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in AssistantSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -2144,23 +2304,28 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class AssistantState(): +class AssistantState: """ Status information about the skills for the assistant. Included in responses only if **status**=`Available`. - :attr bool action_disabled: Whether the action skill is disabled in the draft + :param bool action_disabled: Whether the action skill is disabled in the draft environment. - :attr bool dialog_disabled: Whether the dialog skill is disabled in the draft + :param bool dialog_disabled: Whether the dialog skill is disabled in the draft environment. """ - def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: + def __init__( + self, + action_disabled: bool, + dialog_disabled: bool, + ) -> None: """ Initialize a AssistantState object. @@ -2176,14 +2341,14 @@ def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: def from_dict(cls, _dict: Dict) -> 'AssistantState': """Initialize a AssistantState object from a json dictionary.""" args = {} - if 'action_disabled' in _dict: - args['action_disabled'] = _dict.get('action_disabled') + if (action_disabled := _dict.get('action_disabled')) is not None: + args['action_disabled'] = action_disabled else: raise ValueError( 'Required property \'action_disabled\' not present in AssistantState JSON' ) - if 'dialog_disabled' in _dict: - args['dialog_disabled'] = _dict.get('dialog_disabled') + if (dialog_disabled := _dict.get('dialog_disabled')) is not None: + args['dialog_disabled'] = dialog_disabled else: raise ValueError( 'Required property \'dialog_disabled\' not present in AssistantState JSON' @@ -2225,24 +2390,28 @@ def __ne__(self, other: 'AssistantState') -> bool: return not self == other -class BaseEnvironmentOrchestration(): +class BaseEnvironmentOrchestration: """ The search skill orchestration settings for the environment. - :attr bool search_skill_fallback: (optional) Whether assistants deployed to the - environment fall back to a search skill when responding to messages that do not - match any intent. If no search skill is configured for the assistant, this - property is ignored. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ - def __init__(self, *, search_skill_fallback: bool = None) -> None: + def __init__( + self, + *, + search_skill_fallback: Optional[bool] = None, + ) -> None: """ Initialize a BaseEnvironmentOrchestration object. - :param bool search_skill_fallback: (optional) Whether assistants deployed - to the environment fall back to a search skill when responding to messages - that do not match any intent. If no search skill is configured for the - assistant, this property is ignored. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ self.search_skill_fallback = search_skill_fallback @@ -2250,8 +2419,9 @@ def __init__(self, *, search_skill_fallback: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentOrchestration': """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" args = {} - if 'search_skill_fallback' in _dict: - args['search_skill_fallback'] = _dict.get('search_skill_fallback') + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) @classmethod @@ -2286,14 +2456,18 @@ def __ne__(self, other: 'BaseEnvironmentOrchestration') -> bool: return not self == other -class BaseEnvironmentReleaseReference(): +class BaseEnvironmentReleaseReference: """ An object describing the release that is currently deployed in the environment. - :attr str release: (optional) The name of the deployed release. + :param str release: (optional) The name of the deployed release. """ - def __init__(self, *, release: str = None) -> None: + def __init__( + self, + *, + release: Optional[str] = None, + ) -> None: """ Initialize a BaseEnvironmentReleaseReference object. @@ -2305,8 +2479,8 @@ def __init__(self, *, release: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentReleaseReference': """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') + if (release := _dict.get('release')) is not None: + args['release'] = release return cls(**args) @classmethod @@ -2340,23 +2514,25 @@ def __ne__(self, other: 'BaseEnvironmentReleaseReference') -> bool: return not self == other -class BulkClassifyOutput(): +class BulkClassifyOutput: """ BulkClassifyOutput. - :attr BulkClassifyUtterance input: (optional) The user input utterance to + :param BulkClassifyUtterance input: (optional) The user input utterance to classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the utterance. """ - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: """ Initialize a BulkClassifyOutput object. @@ -2375,16 +2551,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] return cls(**args) @classmethod @@ -2437,15 +2609,19 @@ def __ne__(self, other: 'BulkClassifyOutput') -> bool: return not self == other -class BulkClassifyResponse(): +class BulkClassifyResponse: """ BulkClassifyResponse. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that + :param List[BulkClassifyOutput] output: (optional) An array of objects that contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: """ Initialize a BulkClassifyResponse object. @@ -2458,10 +2634,8 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(v) for v in _dict.get('output') - ] + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] return cls(**args) @classmethod @@ -2501,14 +2675,17 @@ def __ne__(self, other: 'BulkClassifyResponse') -> bool: return not self == other -class BulkClassifyUtterance(): +class BulkClassifyUtterance: """ The user input utterance to classify. - :attr str text: The text of the input utterance. + :param str text: The text of the input utterance. """ - def __init__(self, text: str) -> None: + def __init__( + self, + text: str, + ) -> None: """ Initialize a BulkClassifyUtterance object. @@ -2520,8 +2697,8 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in BulkClassifyUtterance JSON' @@ -2559,16 +2736,21 @@ def __ne__(self, other: 'BulkClassifyUtterance') -> bool: return not self == other -class CaptureGroup(): +class CaptureGroup: """ CaptureGroup. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a CaptureGroup object. @@ -2583,13 +2765,13 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if (group := _dict.get('group')) is not None: + args['group'] = group else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -2625,18 +2807,21 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other -class ChannelTransferInfo(): +class ChannelTransferInfo: """ Information used by an integration to transfer the conversation to a different channel. - :attr ChannelTransferTarget target: An object specifying target channels + :param ChannelTransferTarget target: An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: """ Initialize a ChannelTransferInfo object. @@ -2651,9 +2836,8 @@ def __init__(self, target: 'ChannelTransferTarget') -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) else: raise ValueError( 'Required property \'target\' not present in ChannelTransferInfo JSON' @@ -2694,17 +2878,21 @@ def __ne__(self, other: 'ChannelTransferInfo') -> bool: return not self == other -class ChannelTransferTarget(): +class ChannelTransferTarget: """ An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: """ Initialize a ChannelTransferTarget object. @@ -2717,9 +2905,8 @@ def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) return cls(**args) @classmethod @@ -2756,14 +2943,18 @@ def __ne__(self, other: 'ChannelTransferTarget') -> bool: return not self == other -class ChannelTransferTargetChat(): +class ChannelTransferTargetChat: """ Information for transferring to the web chat integration. - :attr str url: (optional) The URL of the target web chat. + :param str url: (optional) The URL of the target web chat. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: """ Initialize a ChannelTransferTargetChat object. @@ -2775,8 +2966,8 @@ def __init__(self, *, url: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod @@ -2810,24 +3001,26 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class DialogLogMessage(): +class DialogLogMessage: """ Dialog log message details. - :attr str level: The severity of the log message. - :attr str message: The text of the log message. - :attr str code: A code that indicates the category to which the error message + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error message belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog + :param LogMessageSource source: (optional) An object that identifies the dialog element that generated the error message. """ - def __init__(self, - level: str, - message: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + level: str, + message: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: """ Initialize a DialogLogMessage object. @@ -2847,26 +3040,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') + if (level := _dict.get('level')) is not None: + args['level'] = level else: raise ValueError( 'Required property \'level\' not present in DialogLogMessage JSON' ) - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message else: raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in DialogLogMessage JSON' ) - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) return cls(**args) @classmethod @@ -2912,32 +3105,35 @@ class LevelEnum(str, Enum): """ The severity of the log message. """ + INFO = 'info' ERROR = 'error' WARN = 'warn' -class DialogNodeAction(): +class DialogNodeAction: """ DialogNodeAction. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result of the action is stored. - :attr str credentials: (optional) The name of the context variable that the + :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeAction object. @@ -2960,24 +3156,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials return cls(**args) @classmethod @@ -3023,20 +3219,25 @@ class TypeEnum(str, Enum): """ The type of action to invoke. """ + CLIENT = 'client' SERVER = 'server' WEB_ACTION = 'web-action' CLOUD_FUNCTION = 'cloud-function' -class DialogNodeOutputConnectToAgentTransferInfo(): +class DialogNodeOutputConnectToAgentTransferInfo: """ Routing or other contextual information to be used by target service desk systems. - :attr dict target: (optional) + :param dict target: (optional) """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: """ Initialize a DialogNodeOutputConnectToAgentTransferInfo object. @@ -3049,8 +3250,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (target := _dict.get('target')) is not None: + args['target'] = target return cls(**args) @classmethod @@ -3086,17 +3287,20 @@ def __ne__(self, return not self == other -class DialogNodeOutputOptionsElement(): +class DialogNodeOutputOptionsElement: """ DialogNodeOutputOptionsElement. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding option. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -3112,15 +3316,14 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' @@ -3163,16 +3366,20 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: return not self == other -class DialogNodeOutputOptionsElementValue(): +class DialogNodeOutputOptionsElementValue: """ An object defining the message input to be sent to the assistant if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -3185,8 +3392,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) return cls(**args) @classmethod @@ -3223,22 +3430,24 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodeVisited(): +class DialogNodeVisited: """ An objects containing detailed diagnostic information about a dialog node that was visited during processing of the input message. - :attr str dialog_node: (optional) A dialog node that was visited during + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeVisited object. @@ -3256,12 +3465,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': """Initialize a DialogNodeVisited object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions return cls(**args) @classmethod @@ -3299,28 +3508,30 @@ def __ne__(self, other: 'DialogNodeVisited') -> bool: return not self == other -class DialogSuggestion(): +class DialogSuggestion: """ DialogSuggestion. - :attr str label: The user-facing label for the suggestion. This label is taken + :param str label: The user-facing label for the suggestion. This label is taken from the **title** or **user_label** property of the corresponding dialog node, depending on the disambiguation options. - :attr DialogSuggestionValue value: An object defining the message input to be + :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. **Note:** This entire message input object must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + :param dict output: (optional) The dialog output that will be returned from the + watsonx Assistant service if the user selects the corresponding option. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None) -> None: + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + ) -> None: """ Initialize a DialogSuggestion object. @@ -3334,7 +3545,7 @@ def __init__(self, body of the next message sent to the assistant. Do not modify or remove any of the included properties. :param dict output: (optional) The dialog output that will be returned from - the Watson Assistant service if the user selects the corresponding option. + the watsonx Assistant service if the user selects the corresponding option. """ self.label = label self.value = value @@ -3344,20 +3555,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') + if (output := _dict.get('output')) is not None: + args['output'] = output return cls(**args) @classmethod @@ -3398,7 +3609,7 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionValue(): +class DialogSuggestionValue: """ An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -3406,11 +3617,15 @@ class DialogSuggestionValue(): the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: """ Initialize a DialogSuggestionValue object. @@ -3423,8 +3638,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) return cls(**args) @classmethod @@ -3461,49 +3676,53 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Environment(): +class Environment: """ Environment. - :attr str name: (optional) The name of the environment. - :attr str description: (optional) The description of the environment. - :attr str assistant_id: (optional) The assistant ID of the assistant the + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param str assistant_id: (optional) The assistant ID of the assistant the environment is associated with. - :attr str environment_id: (optional) The environment ID of the environment. - :attr str environment: (optional) The type of the environment. All environments + :param str environment_id: (optional) The environment ID of the environment. + :param str environment: (optional) The type of the environment. All environments other than the `draft` and `live` environments have the type `staging`. - :attr BaseEnvironmentReleaseReference release_reference: (optional) An object + :param BaseEnvironmentReleaseReference release_reference: (optional) An object describing the release that is currently deployed in the environment. - :attr BaseEnvironmentOrchestration orchestration: (optional) The search skill + :param BaseEnvironmentOrchestration orchestration: The search skill orchestration settings for the environment. - :attr int session_timeout: The session inactivity timeout setting for the + :param int session_timeout: The session inactivity timeout setting for the environment (in seconds). - :attr List[IntegrationReference] integration_references: (optional) An array of + :param List[IntegrationReference] integration_references: (optional) An array of objects describing the integrations that exist in the environment. - :attr List[EnvironmentSkill] skill_references: An array of objects identifying + :param List[EnvironmentSkill] skill_references: An array of objects identifying the skills (such as action and dialog) that exist in the environment. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - session_timeout: int, - skill_references: List['EnvironmentSkill'], - *, - name: str = None, - description: str = None, - assistant_id: str = None, - environment_id: str = None, - environment: str = None, - release_reference: 'BaseEnvironmentReleaseReference' = None, - orchestration: 'BaseEnvironmentOrchestration' = None, - integration_references: List['IntegrationReference'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + orchestration: 'BaseEnvironmentOrchestration', + session_timeout: int, + skill_references: List['EnvironmentSkill'], + *, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_id: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + release_reference: Optional['BaseEnvironmentReleaseReference'] = None, + integration_references: Optional[List['IntegrationReference']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Environment object. + :param BaseEnvironmentOrchestration orchestration: The search skill + orchestration settings for the environment. :param int session_timeout: The session inactivity timeout setting for the environment (in seconds). :param List[EnvironmentSkill] skill_references: An array of objects @@ -3529,47 +3748,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') - if 'release_reference' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment + if (release_reference := _dict.get('release_reference')) is not None: args[ 'release_reference'] = BaseEnvironmentReleaseReference.from_dict( - _dict.get('release_reference')) - if 'orchestration' in _dict: + release_reference) + if (orchestration := _dict.get('orchestration')) is not None: args['orchestration'] = BaseEnvironmentOrchestration.from_dict( - _dict.get('orchestration')) - if 'session_timeout' in _dict: - args['session_timeout'] = _dict.get('session_timeout') + orchestration) + else: + raise ValueError( + 'Required property \'orchestration\' not present in Environment JSON' + ) + if (session_timeout := _dict.get('session_timeout')) is not None: + args['session_timeout'] = session_timeout else: raise ValueError( 'Required property \'session_timeout\' not present in Environment JSON' ) - if 'integration_references' in _dict: + if (integration_references := + _dict.get('integration_references')) is not None: args['integration_references'] = [ IntegrationReference.from_dict(v) - for v in _dict.get('integration_references') + for v in integration_references ] - if 'skill_references' in _dict: + if (skill_references := _dict.get('skill_references')) is not None: args['skill_references'] = [ - EnvironmentSkill.from_dict(v) - for v in _dict.get('skill_references') + EnvironmentSkill.from_dict(v) for v in skill_references ] else: raise ValueError( 'Required property \'skill_references\' not present in Environment JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -3600,13 +3823,11 @@ def to_dict(self) -> Dict: else: _dict['release_reference'] = getattr( self, 'release_reference').to_dict() - if hasattr(self, 'orchestration') and getattr( - self, 'orchestration') is not None: - if isinstance(getattr(self, 'orchestration'), dict): - _dict['orchestration'] = getattr(self, 'orchestration') + if hasattr(self, 'orchestration') and self.orchestration is not None: + if isinstance(self.orchestration, dict): + _dict['orchestration'] = self.orchestration else: - _dict['orchestration'] = getattr(self, - 'orchestration').to_dict() + _dict['orchestration'] = self.orchestration.to_dict() if hasattr(self, 'session_timeout') and self.session_timeout is not None: _dict['session_timeout'] = self.session_timeout @@ -3653,18 +3874,21 @@ def __ne__(self, other: 'Environment') -> bool: return not self == other -class EnvironmentCollection(): +class EnvironmentCollection: """ EnvironmentCollection. - :attr List[Environment] environments: An array of objects describing the + :param List[Environment] environments: An array of objects describing the environments associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, environments: List['Environment'], - pagination: 'Pagination') -> None: + def __init__( + self, + environments: List['Environment'], + pagination: 'Pagination', + ) -> None: """ Initialize a EnvironmentCollection object. @@ -3680,16 +3904,16 @@ def __init__(self, environments: List['Environment'], def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': """Initialize a EnvironmentCollection object from a json dictionary.""" args = {} - if 'environments' in _dict: + if (environments := _dict.get('environments')) is not None: args['environments'] = [ - Environment.from_dict(v) for v in _dict.get('environments') + Environment.from_dict(v) for v in environments ] else: raise ValueError( 'Required property \'environments\' not present in EnvironmentCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EnvironmentCollection JSON' @@ -3738,21 +3962,23 @@ def __ne__(self, other: 'EnvironmentCollection') -> bool: return not self == other -class EnvironmentReference(): +class EnvironmentReference: """ EnvironmentReference. - :attr str name: (optional) The name of the environment. - :attr str environment_id: (optional) The unique identifier of the environment. - :attr str environment: (optional) The type of the environment. All environments + :param str name: (optional) The name of the environment. + :param str environment_id: (optional) The unique identifier of the environment. + :param str environment: (optional) The type of the environment. All environments other than the draft and live environments have the type `staging`. """ - def __init__(self, - *, - name: str = None, - environment_id: str = None, - environment: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + ) -> None: """ Initialize a EnvironmentReference object. @@ -3766,12 +3992,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': """Initialize a EnvironmentReference object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment return cls(**args) @classmethod @@ -3815,34 +4041,37 @@ class EnvironmentEnum(str, Enum): The type of the environment. All environments other than the draft and live environments have the type `staging`. """ + DRAFT = 'draft' LIVE = 'live' STAGING = 'staging' -class EnvironmentSkill(): +class EnvironmentSkill: """ EnvironmentSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled skill in the draft environment does not handle any messages at run time, and it is not included in saved releases. - :attr str snapshot: (optional) The name of the skill snapshot that is deployed + :param str snapshot: (optional) The name of the skill snapshot that is deployed to the environment (for example, `draft` or `1`). - :attr str skill_reference: (optional) The type of skill identified by the skill + :param str skill_reference: (optional) The type of skill identified by the skill reference. The possible values are `main skill` (for a dialog skill), `actions skill`, and `search skill`. """ - def __init__(self, - skill_id: str, - *, - type: str = None, - disabled: bool = None, - snapshot: str = None, - skill_reference: str = None) -> None: + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + disabled: Optional[bool] = None, + snapshot: Optional[str] = None, + skill_reference: Optional[str] = None, + ) -> None: """ Initialize a EnvironmentSkill object. @@ -3867,20 +4096,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentSkill': """Initialize a EnvironmentSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in EnvironmentSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - if 'skill_reference' in _dict: - args['skill_reference'] = _dict.get('skill_reference') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + if (skill_reference := _dict.get('skill_reference')) is not None: + args['skill_reference'] = skill_reference return cls(**args) @classmethod @@ -3926,20 +4155,26 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class IntegrationReference(): +class IntegrationReference: """ IntegrationReference. - :attr str integration_id: (optional) The integration ID of the integration. - :attr str type: (optional) The type of the integration. + :param str integration_id: (optional) The integration ID of the integration. + :param str type: (optional) The type of the integration. """ - def __init__(self, *, integration_id: str = None, type: str = None) -> None: + def __init__( + self, + *, + integration_id: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a IntegrationReference object. @@ -3954,10 +4189,10 @@ def __init__(self, *, integration_id: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'IntegrationReference': """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if 'integration_id' in _dict: - args['integration_id'] = _dict.get('integration_id') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (integration_id := _dict.get('integration_id')) is not None: + args['integration_id'] = integration_id + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -3993,50 +4228,51 @@ def __ne__(self, other: 'IntegrationReference') -> bool: return not self == other -class Log(): +class Log: """ Log. - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the + :param str log_id: A unique identifier for the logged event. + :param LogRequest request: A message request formatted for the watsonx Assistant + service. + :param LogResponse response: A response from the watsonx Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to the message. - :attr str snapshot: The name of the snapshot (dialog skill version) that + :param str snapshot: The name of the snapshot (dialog skill version) that responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the message. - :attr str language: The language of the assistant to which the message request + :param str language: The language of the assistant to which the message request was made. - :attr str customer_id: (optional) The customer ID specified for the message, if + :param str customer_id: (optional) The customer ID specified for the message, if any. """ - def __init__(self, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, - *, - customer_id: str = None) -> None: + def __init__( + self, + log_id: str, + request: 'LogRequest', + response: 'LogResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: Optional[str] = None, + ) -> None: """ Initialize a Log object. :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. + :param LogRequest request: A message request formatted for the watsonx + Assistant service. + :param LogResponse response: A response from the watsonx Assistant service. :param str assistant_id: Unique identifier of the assistant. :param str session_id: The ID of the session the message was part of. :param str skill_id: The unique identifier of the skill that responded to @@ -4067,60 +4303,60 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) + if (request := _dict.get('request')) is not None: + args['request'] = LogRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) + if (response := _dict.get('response')) is not None: + args['response'] = LogResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id else: raise ValueError( 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id else: raise ValueError( 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot else: raise ValueError( 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp else: raise ValueError( 'Required property \'request_timestamp\' not present in Log JSON' ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp else: raise ValueError( 'Required property \'response_timestamp\' not present in Log JSON' ) - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id return cls(**args) @classmethod @@ -4183,16 +4419,20 @@ def __ne__(self, other: 'Log') -> bool: return not self == other -class LogCollection(): +class LogCollection: """ LogCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: """ Initialize a LogCollection object. @@ -4208,14 +4448,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in LogCollection JSON' @@ -4264,13 +4503,13 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other -class LogMessageSource(): +class LogMessageSource: """ An object that identifies the dialog element that generated the error message. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a LogMessageSource object. @@ -4288,13 +4527,11 @@ def from_dict(cls, _dict: Dict) -> 'LogMessageSource': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) + msg = "Cannot convert dictionary into an instance of base class 'LogMessageSource'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) raise Exception(msg) @classmethod @@ -4324,22 +4561,24 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class LogPagination(): +class LogPagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str next_url: (optional) The URL that will return the next page of + :param str next_url: (optional) The URL that will return the next page of results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a LogPagination object. @@ -4357,12 +4596,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -4400,72 +4639,95 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class MessageContext(): +class LogRequest: """ - MessageContext. + A message request formatted for the watsonx Assistant service. - :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :attr MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :attr dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the input + text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ - def __init__(self, - *, - global_: 'MessageContextGlobal' = None, - skills: 'MessageContextSkills' = None, - integrations: dict = None) -> None: + def __init__( + self, + *, + input: Optional['LogRequestInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + ) -> None: """ - Initialize a MessageContext object. + Initialize a LogRequest object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.input = input + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogRequest': + """Initialize a LogRequest object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (input := _dict.get('input')) is not None: + args['input'] = LogRequestInput.from_dict(input) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a LogRequest object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -4473,69 +4735,175 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this LogRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'LogRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContext') -> bool: + def __ne__(self, other: 'LogRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal(): +class LogRequestInput: """ - Session context data that is shared by all skills used by the assistant. + An input object that includes the input text. All private data is masked or removed. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: - """ - Initialize a MessageContextGlobal object. - - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, + ) -> None: """ - self.system = system - self.session_id = session_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" - args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" - return cls.from_dict(_dict) + Initialize a LogRequestInput object. - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogRequestInput': + """Initialize a LogRequestInput object from a json dictionary.""" + args = {} + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogRequestInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -4543,69 +4911,126 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this LogRequestInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'LogRequestInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'LogRequestInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' -class MessageContextGlobalStateless(): + +class LogResponse: """ - Session context data that is shared by all skills used by the assistant. + A response from the watsonx Assistant service. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :param LogResponseOutput output: Assistant output to be rendered or processed by + the client. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__( + self, + output: 'LogResponseOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + ) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a LogResponse object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param LogResponseOutput output: Assistant output to be rendered or + processed by the client. All private data is masked or removed. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. """ - self.system = system - self.session_id = session_id + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponse': + """Initialize a LogResponse object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (output := _dict.get('output')) is not None: + args['output'] = LogResponseOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in LogResponse JSON') + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in LogResponse JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a LogResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -4613,194 +5038,157 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalStateless object.""" + """Return a `str` version of this LogResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'LogResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'LogResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalSystem(): +class LogResponseOutput: """ - Built-in system properties that apply to all skills used by the assistant. + Assistant output to be rendered or processed by the client. All private data is masked + or removed. - :attr str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented - with each turn of the conversation. A value of 1 indicates that this is the the - first turn of a new conversation, which can affect the behavior of some skills - (for example, triggering the start node of a dialog). - :attr str locale: (optional) The language code for localization in the user - input. The specified locale overrides the default for the assistant, and is used - for interpreting entity values in user input such as date values. For example, - `04/03/2018` might be interpreted either as April 3 or March 4, depending on the - locale. - This property is included only if the new system entities are enabled for the - skill. - :attr str reference_time: (optional) The base time for interpreting any relative - time mentions in the user input. The specified time overrides the current server - time, and is used to calculate times mentioned in relative terms such as `now` - or `tomorrow`. This can be useful for simulating past or future times for - testing purposes, or when analyzing documents such as news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :attr str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - def __init__(self, - *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + def __init__( + self, + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + ) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a LogResponseOutput object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented with each turn of the conversation. A value of 1 indicates that - this is the the first turn of a new conversation, which can affect the - behavior of some skills (for example, triggering the start node of a - dialog). - :param str locale: (optional) The language code for localization in the - user input. The specified locale overrides the default for the assistant, - and is used for interpreting entity values in user input such as date - values. For example, `04/03/2018` might be interpreted either as April 3 or - March 4, depending on the locale. - This property is included only if the new system entities are enabled for - the skill. - :param str reference_time: (optional) The base time for interpreting any - relative time mentions in the user input. The specified time overrides the - current server time, and is used to calculate times mentioned in relative - terms such as `now` or `tomorrow`. This can be useful for simulating past - or future times for testing purposes, or when analyzing documents such as - news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponseOutput': + """Initialize a LogResponseOutput object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - if 'turn_count' in _dict: - args['turn_count'] = _dict.get('turn_count') - if 'locale' in _dict: - args['locale'] = _dict.get('locale') - if 'reference_time' in _dict: - args['reference_time'] = _dict.get('reference_time') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a LogResponseOutput object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'turn_count') and self.turn_count is not None: - _dict['turn_count'] = self.turn_count - if hasattr(self, 'locale') and self.locale is not None: - _dict['locale'] = self.locale - if hasattr(self, 'reference_time') and self.reference_time is not None: - _dict['reference_time'] = self.reference_time - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() return _dict def _to_dict(self): @@ -4808,70 +5196,136 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this LogResponseOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'LogResponseOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'LogResponseOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, Enum): + +class MessageContext: + """ + MessageContext. + + :param MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__( + self, + *, + global_: Optional['MessageContextGlobal'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: """ - The language code for localization in the user input. The specified locale - overrides the default for the assistant, and is used for interpreting entity - values in user input such as date values. For example, `04/03/2018` might be - interpreted either as April 3 or March 4, depending on the locale. - This property is included only if the new system entities are enabled for the - skill. + Initialize a MessageContext object. + + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - EN_US = 'en-us' - EN_CA = 'en-ca' - EN_GB = 'en-gb' - AR_AR = 'ar-ar' - CS_CZ = 'cs-cz' - DE_DE = 'de-de' - ES_ES = 'es-es' - FR_FR = 'fr-fr' - IT_IT = 'it-it' - JA_JP = 'ja-jp' - KO_KR = 'ko-kr' - NL_NL = 'nl-nl' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' + self.global_ = global_ + self.skills = skills + self.integrations = integrations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" + args = {} + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContext object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContext object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContext') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other -class MessageContextSkillAction(): +class MessageContextActionSkill: """ - Context variables that are used by the action skill. + Context variables that are used by the action skill. Private variables are persisted, + but not shown. - :attr dict user_defined: (optional) An object containing any arbitrary variables - that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by the skill. - :attr dict action_variables: (optional) An object containing action variables. + :param dict action_variables: (optional) An object containing action variables. Action variables can be accessed only by steps in the same action, and do not persist after the action ends. - :attr dict skill_variables: (optional) An object containing skill variables. (In - the Watson Assistant user interface, skill variables are called _session + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session variables_.) Skill variables can be accessed by any action and persist for the duration of the session. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None, - action_variables: dict = None, - skill_variables: dict = None) -> None: + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + ) -> None: """ - Initialize a MessageContextSkillAction object. + Initialize a MessageContextActionSkill object. :param dict user_defined: (optional) An object containing any arbitrary variables that can be read and written by a particular skill. @@ -4881,7 +5335,7 @@ def __init__(self, variables. Action variables can be accessed only by steps in the same action, and do not persist after the action ends. :param dict skill_variables: (optional) An object containing skill - variables. (In the Watson Assistant user interface, skill variables are + variables. (In the watsonx Assistant user interface, skill variables are called _session variables_.) Skill variables can be accessed by any action and persist for the duration of the session. """ @@ -4891,23 +5345,22 @@ def __init__(self, self.skill_variables = skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': - """Initialize a MessageContextSkillAction object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextActionSkill': + """Initialize a MessageContextActionSkill object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) - if 'action_variables' in _dict: - args['action_variables'] = _dict.get('action_variables') - if 'skill_variables' in _dict: - args['skill_variables'] = _dict.get('skill_variables') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillAction object from a json dictionary.""" + """Initialize a MessageContextActionSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -4933,36 +5386,38 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillAction object.""" + """Return a `str` version of this MessageContextActionSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillAction') -> bool: + def __eq__(self, other: 'MessageContextActionSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkillAction') -> bool: + def __ne__(self, other: 'MessageContextActionSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillDialog(): +class MessageContextDialogSkill: """ Context variables that are used by the dialog skill. - :attr dict user_defined: (optional) An object containing any arbitrary variables - that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by the skill. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + ) -> None: """ - Initialize a MessageContextSkillDialog object. + Initialize a MessageContextDialogSkill object. :param dict user_defined: (optional) An object containing any arbitrary variables that can be read and written by a particular skill. @@ -4973,19 +5428,18 @@ def __init__(self, self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': - """Initialize a MessageContextSkillDialog object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextDialogSkill': + """Initialize a MessageContextDialogSkill object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillDialog object from a json dictionary.""" + """Initialize a MessageContextDialogSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -5005,173 +5459,267 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillDialog object.""" + """Return a `str` version of this MessageContextDialogSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillDialog') -> bool: + def __eq__(self, other: 'MessageContextDialogSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkillDialog') -> bool: + def __ne__(self, other: 'MessageContextDialogSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillSystem(): +class MessageContextGlobal: """ - System context data used by the skill. + Session context data that is shared by all skills used by the assistant. - :attr str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The session ID. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a MessageContextGlobal object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a MessageContextGlobal object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkills(): +class MessageContextGlobalSystem: """ - Context data specific to particular skills used by the assistant. + Built-in system properties that apply to all skills used by the assistant. - :attr MessageContextSkillDialog main_skill: (optional) Context variables that - are used by the dialog skill. - :attr MessageContextSkillAction actions_skill: (optional) Context variables that - are used by the action skill. + :param str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically incremented + with each turn of the conversation. A value of 1 indicates that this is the the + first turn of a new conversation, which can affect the behavior of some skills + (for example, triggering the start node of a dialog). + :param str locale: (optional) The language code for localization in the user + input. The specified locale overrides the default for the assistant, and is used + for interpreting entity values in user input such as date values. For example, + `04/03/2018` might be interpreted either as April 3 or March 4, depending on the + locale. + This property is included only if the new system entities are enabled for the + skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative terms + such as `now` or `tomorrow`. This can be useful for simulating past or future + times for testing purposes, or when analyzing documents such as news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :param str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - def __init__(self, - *, - main_skill: 'MessageContextSkillDialog' = None, - actions_skill: 'MessageContextSkillAction' = None) -> None: + def __init__( + self, + *, + timezone: Optional[str] = None, + user_id: Optional[str] = None, + turn_count: Optional[int] = None, + locale: Optional[str] = None, + reference_time: Optional[str] = None, + session_start_time: Optional[str] = None, + state: Optional[str] = None, + skip_user_input: Optional[bool] = None, + ) -> None: """ - Initialize a MessageContextSkills object. + Initialize a MessageContextGlobalSystem object. - :param MessageContextSkillDialog main_skill: (optional) Context variables - that are used by the dialog skill. - :param MessageContextSkillAction actions_skill: (optional) Context - variables that are used by the action skill. + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented with each turn of the conversation. A value of 1 indicates that + this is the the first turn of a new conversation, which can affect the + behavior of some skills (for example, triggering the start node of a + dialog). + :param str locale: (optional) The language code for localization in the + user input. The specified locale overrides the default for the assistant, + and is used for interpreting entity values in user input such as date + values. For example, `04/03/2018` might be interpreted either as April 3 or + March 4, depending on the locale. + This property is included only if the new system entities are enabled for + the skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative + terms such as `now` or `tomorrow`. This can be useful for simulating past + or future times for testing purposes, or when analyzing documents such as + news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - self.main_skill = main_skill - self.actions_skill = actions_skill + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': - """Initialize a MessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if 'main skill' in _dict: - args['main_skill'] = MessageContextSkillDialog.from_dict( - _dict.get('main skill')) - if 'actions skill' in _dict: - args['actions_skill'] = MessageContextSkillAction.from_dict( - _dict.get('actions skill')) + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (turn_count := _dict.get('turn_count')) is not None: + args['turn_count'] = turn_count + if (locale := _dict.get('locale')) is not None: + args['locale'] = locale + if (reference_time := _dict.get('reference_time')) is not None: + args['reference_time'] = reference_time + if (session_start_time := _dict.get('session_start_time')) is not None: + args['session_start_time'] = session_start_time + if (state := _dict.get('state')) is not None: + args['state'] = state + if (skip_user_input := _dict.get('skip_user_input')) is not None: + args['skip_user_input'] = skip_user_input return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkills object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill - else: - _dict['actions skill'] = self.actions_skill.to_dict() + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'turn_count') and self.turn_count is not None: + _dict['turn_count'] = self.turn_count + if hasattr(self, 'locale') and self.locale is not None: + _dict['locale'] = self.locale + if hasattr(self, 'reference_time') and self.reference_time is not None: + _dict['reference_time'] = self.reference_time + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -5179,86 +5727,207 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkills object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkills') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkills') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, Enum): + """ + The language code for localization in the user input. The specified locale + overrides the default for the assistant, and is used for interpreting entity + values in user input such as date values. For example, `04/03/2018` might be + interpreted either as April 3 or March 4, depending on the locale. + This property is included only if the new system entities are enabled for the + skill. + """ + + EN_US = 'en-us' + EN_CA = 'en-ca' + EN_GB = 'en-gb' + AR_AR = 'ar-ar' + CS_CZ = 'cs-cz' + DE_DE = 'de-de' + ES_ES = 'es-es' + FR_FR = 'fr-fr' + IT_IT = 'it-it' + JA_JP = 'ja-jp' + KO_KR = 'ko-kr' + NL_NL = 'nl-nl' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + -class MessageContextStateless(): +class MessageContextSkillSystem: """ - MessageContextStateless. + System context data used by the skill. - :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. - :attr MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :attr dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. """ - def __init__(self, - *, - global_: 'MessageContextGlobalStateless' = None, - skills: 'MessageContextSkills' = None, - integrations: dict = None) -> None: + # The set of defined properties for the class + _properties = frozenset(['state']) + + def __init__( + self, + *, + state: Optional[str] = None, + **kwargs, + ) -> None: """ - Initialize a MessageContextStateless object. + Initialize a MessageContextSkillSystem object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param **kwargs: (optional) Any additional properties. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (state := _dict.get('state')) is not None: + args['state'] = state + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a MessageContextSkillSystem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ - else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkills: + """ + Context data specific to particular skills used by the assistant. + + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context variables + that are used by the action skill. Private variables are persisted, but not + shown. + """ + + def __init__( + self, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional['MessageContextActionSkill'] = None, + ) -> None: + """ + Initialize a MessageContextSkills object. + + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context + variables that are used by the action skill. Private variables are + persisted, but not shown. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" + args = {} + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args['actions_skill'] = MessageContextActionSkill.from_dict( + actions_skill) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -5266,61 +5935,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextStateless') -> bool: + def __ne__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInput(): +class MessageInput: """ An input object that includes the input text. - :attr str message_type: (optional) The type of the message: + :param str message_type: (optional) The type of the message: - `text`: The user input is processed normally by the assistant. - `search`: Only search results are returned. (Any dialog or action skill is bypassed.) **Note:** A `search` message results in an error if no search skill is configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of multimedia attachments to be sent with the message. Attachments are not processed by the assistant itself, but can be sent to external services by webhooks. **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :attr RequestAnalytics analytics: (optional) An optional object containing + :param RequestAnalytics analytics: (optional) An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. - :attr MessageInputOptions options: (optional) Optional properties that control + :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. """ - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - analytics: 'RequestAnalytics' = None, - options: 'MessageInputOptions' = None) -> None: + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, + ) -> None: """ Initialize a MessageInput object. @@ -5365,31 +6036,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') + MessageInputAttachment.from_dict(v) for v in attachments ] - if 'analytics' in _dict: - args['analytics'] = RequestAnalytics.from_dict( - _dict.get('analytics')) - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) return cls(**args) @classmethod @@ -5469,20 +6133,26 @@ class MessageTypeEnum(str, Enum): **Note:** A `search` message results in an error if no search skill is configured for the assistant. """ + TEXT = 'text' SEARCH = 'search' -class MessageInputAttachment(): +class MessageInputAttachment: """ A reference to a media file to be sent as an attachment with the message. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME type) + of the attachment. """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__( + self, + url: str, + *, + media_type: Optional[str] = None, + ) -> None: """ Initialize a MessageInputAttachment object. @@ -5497,14 +6167,14 @@ def __init__(self, url: str, *, media_type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': """Initialize a MessageInputAttachment object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in MessageInputAttachment JSON' ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if (media_type := _dict.get('media_type')) is not None: + args['media_type'] = media_type return cls(**args) @classmethod @@ -5540,41 +6210,51 @@ def __ne__(self, other: 'MessageInputAttachment') -> bool: return not self == other -class MessageInputOptions(): +class MessageInputOptions: """ Optional properties that control how the assistant responds. - :attr bool restart: (optional) Whether to restart dialog processing at the root + :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic + :param bool debug: (optional) Whether to return additional diagnostic information. Set to `true` to return additional information in the `output.debug` property. If you also specify **return_context**=`true`, the returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full + :param bool return_context: (optional) Whether to return session context with + the response. If you specify `true`, the response includes the `context` + property. If you also specify **debug**=`true`, the returned skill context + includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including full conversation state. If you specify `true`, the response includes the `context` property, and the skill context includes the `system.state` property. **Note:** If **export**=`true`, the context is returned regardless of the value of **return_context**. """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + return_context: Optional[bool] = None, + export: Optional[bool] = None, + ) -> None: """ Initialize a MessageInputOptions object. @@ -5583,6 +6263,14 @@ def __init__(self, This does not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. @@ -5603,6 +6291,7 @@ def __init__(self, """ self.restart = restart self.alternate_intents = alternate_intents + self.async_callout = async_callout self.spelling = spelling self.debug = debug self.return_context = return_context @@ -5612,19 +6301,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug + if (return_context := _dict.get('return_context')) is not None: + args['return_context'] = return_context + if (export := _dict.get('export')) is not None: + args['export'] = export return cls(**args) @classmethod @@ -5640,6 +6330,8 @@ def to_dict(self) -> Dict: if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout if hasattr(self, 'spelling') and self.spelling is not None: if isinstance(self.spelling, dict): _dict['spelling'] = self.spelling @@ -5672,19 +6364,19 @@ def __ne__(self, other: 'MessageInputOptions') -> bool: return not self == other -class MessageInputOptionsSpelling(): +class MessageInputOptionsSpelling: """ Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. - :attr bool suggestions: (optional) Whether to use spelling correction when + :param bool suggestions: (optional) Whether to use spelling correction when processing the input. If spelling correction is used and **auto_correct** is `true`, any spelling corrections are automatically applied to the user input. If **auto_correct** is `false`, any suggested corrections are returned in the **output.spelling** property. This property overrides the value of the **spelling_suggestions** property in the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when + :param bool auto_correct: (optional) Whether to use autocorrection when processing the input. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **output.spelling** property of the message response. This property @@ -5692,10 +6384,12 @@ class MessageInputOptionsSpelling(): settings for the skill. """ - def __init__(self, - *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + def __init__( + self, + *, + suggestions: Optional[bool] = None, + auto_correct: Optional[bool] = None, + ) -> None: """ Initialize a MessageInputOptionsSpelling object. @@ -5720,10 +6414,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if (suggestions := _dict.get('suggestions')) is not None: + args['suggestions'] = suggestions + if (auto_correct := _dict.get('auto_correct')) is not None: + args['auto_correct'] = auto_correct return cls(**args) @classmethod @@ -5759,84 +6453,142 @@ def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: return not self == other -class MessageInputOptionsStateless(): +class MessageOutput: """ - Optional properties that control how the assistant responds. + Assistant output to be rendered or processed by the client. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + def __init__( + self, + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + ) -> None: """ - Initialize a MessageInputOptionsStateless object. + Initialize a MessageOutput object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a MessageOutput object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined if hasattr(self, 'spelling') and self.spelling is not None: if isinstance(self.spelling, dict): _dict['spelling'] = self.spelling else: _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -5844,180 +6596,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this MessageOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputStateless(): +class MessageOutputDebug: """ - An input object that includes the input text. + Additional detailed information about a message response and how it was generated. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :attr RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :attr MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - analytics: 'RequestAnalytics' = None, - options: 'MessageInputOptionsStateless' = None) -> None: + def __init__( + self, + *, + nodes_visited: Optional[List['DialogNodeVisited']] = None, + log_messages: Optional[List['DialogLogMessage']] = None, + branch_exited: Optional[bool] = None, + branch_exited_reason: Optional[str] = None, + turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, + ) -> None: """ - Initialize a MessageInputStateless object. + Initialize a MessageOutputDebug object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) for v in nodes_visited ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') + if (log_messages := _dict.get('log_messages')) is not None: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in log_messages ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') + if (branch_exited := _dict.get('branch_exited')) is not None: + args['branch_exited'] = branch_exited + if (branch_exited_reason := + _dict.get('branch_exited_reason')) is not None: + args['branch_exited_reason'] = branch_exited_reason + if (turn_events := _dict.get('turn_events')) is not None: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events ] - if 'analytics' in _dict: - args['analytics'] = RequestAnalytics.from_dict( - _dict.get('analytics')) - if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( - _dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a MessageOutputDebug object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: if isinstance(v, dict): - intents_list.append(v) + nodes_visited_list.append(v) else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: if isinstance(v, dict): - entities_list.append(v) + log_messages_list.append(v) else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: if isinstance(v, dict): - attachments_list.append(v) + turn_events_list.append(v) else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list return _dict def _to_dict(self): @@ -6025,385 +6730,75 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputStateless') -> bool: + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + class BranchExitedReasonEnum(str, Enum): """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. """ - TEXT = 'text' - SEARCH = 'search' + COMPLETED = 'completed' + FALLBACK = 'fallback' -class MessageOutput(): + +class MessageOutputDebugTurnEvent: """ - Assistant output to be rendered or processed by the client. + MessageOutputDebugTurnEvent. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + def __init__(self,) -> None: """ - Initialize a MessageOutput object. + Initialize a MessageOutputDebugTurnEvent object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" - args = {} - if 'generic' in _dict: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) - for v in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) - return cls(**args) + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'generic') and self.generic is not None: - generic_list = [] - for v in self.generic: - if isinstance(v, dict): - generic_list.append(v) - else: - generic_list.append(v.to_dict()) - _dict['generic'] = generic_list - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'actions') and self.actions is not None: - actions_list = [] - for v in self.actions: - if isinstance(v, dict): - actions_list.append(v) - else: - actions_list.append(v.to_dict()) - _dict['actions'] = actions_list - if hasattr(self, 'debug') and self.debug is not None: - if isinstance(self.debug, dict): - _dict['debug'] = self.debug - else: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageOutput') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MessageOutput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MessageOutputDebug(): - """ - Additional detailed information about a message response and how it was generated. - - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were visited - during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. - :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of - objects containing detailed diagnostic information about dialog nodes and - actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. - """ - - def __init__( - self, - *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None, - turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: - """ - Initialize a MessageOutputDebug object. - - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were visited during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array - of objects containing detailed diagnostic information about dialog nodes - and actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. - """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason - self.turn_events = turn_events - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" - args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(v) - for v in _dict.get('nodes_visited') - ] - if 'log_messages' in _dict: - args['log_messages'] = [ - DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') - ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') - if 'turn_events' in _dict: - args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(v) - for v in _dict.get('turn_events') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: - nodes_visited_list = [] - for v in self.nodes_visited: - if isinstance(v, dict): - nodes_visited_list.append(v) - else: - nodes_visited_list.append(v.to_dict()) - _dict['nodes_visited'] = nodes_visited_list - if hasattr(self, 'log_messages') and self.log_messages is not None: - log_messages_list = [] - for v in self.log_messages: - if isinstance(v, dict): - log_messages_list.append(v) - else: - log_messages_list.append(v.to_dict()) - _dict['log_messages'] = log_messages_list - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason - if hasattr(self, 'turn_events') and self.turn_events is not None: - turn_events_list = [] - for v in self.turn_events: - if isinstance(v, dict): - turn_events_list.append(v) - else: - turn_events_list.append(v.to_dict()) - _dict['turn_events'] = turn_events_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageOutputDebug') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MessageOutputDebug') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - COMPLETED = 'completed' - FALLBACK = 'fallback' - - -class MessageOutputDebugTurnEvent(): - """ - MessageOutputDebugTurnEvent. - - """ - - def __init__(self) -> None: - """ - Initialize a MessageOutputDebugTurnEvent object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" return cls.from_dict(_dict) @classmethod @@ -6438,25 +6833,27 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class MessageOutputSpelling(): +class MessageOutputSpelling: """ Properties describing any spelling corrections in the user input that was received. - :attr str text: (optional) The user input text that was used to generate the + :param str text: (optional) The user input text that was used to generate the response. If spelling autocorrection is enabled, this text reflects any spelling corrections that were applied. - :attr str original_text: (optional) The original user input text. This property + :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input + :param str suggested_text: (optional) Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. """ - def __init__(self, - *, - text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + original_text: Optional[str] = None, + suggested_text: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputSpelling object. @@ -6478,12 +6875,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': """Initialize a MessageOutputSpelling object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text return cls(**args) @classmethod @@ -6521,411 +6918,80 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other -class MessageRequest(): +class Pagination: """ - A stateful message request formatted for the Watson Assistant service. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: """ - Initialize a MessageRequest object. + Initialize a Pagination object. - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.input = input - self.context = context - self.user_id = user_id + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageRequest') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MessageRequest') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MessageResponse(): - """ - A response from the Watson Assistant service. - - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :attr str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. - """ - - def __init__(self, - output: 'MessageOutput', - user_id: str, - *, - context: 'MessageContext' = None) -> None: - """ - Initialize a MessageResponse object. - - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - """ - self.output = output - self.context = context - self.user_id = user_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" - args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MessageResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MessageResponseStateless(): - """ - A stateless response from the Watson Assistant service. - - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. - """ - - def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', - *, - user_id: str = None) -> None: - """ - Initialize a MessageResponseStateless object. - - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - """ - self.output = output - self.context = context - self.user_id = user_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" - args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) - else: - raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' - ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageResponseStateless object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageResponseStateless') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MessageResponseStateless') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Pagination(): - """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). - - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of - results. - :attr int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of - results. - :attr str next_cursor: (optional) A token identifying the next page of results. - """ - - def __init__(self, - refresh_url: str, - *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: - """ - Initialize a Pagination object. - - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. - """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" - args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a Pagination object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -6964,35 +7030,37 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other -class Release(): +class Release: """ Release. - :attr str release: (optional) The name of the release. The name is the version + :param str release: (optional) The name of the release. The name is the version number (an integer), returned as a string. - :attr str description: (optional) The description of the release. - :attr List[EnvironmentReference] environment_references: (optional) An array of + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of objects describing the environments where this release has been deployed. - :attr ReleaseContent content: (optional) An object identifying the versionable + :param ReleaseContent content: (optional) An object identifying the versionable content objects (such as skill snapshots) that are included in the release. - :attr str status: (optional) The current status of the release: + :param str status: (optional) The current status of the release: - **Available**: The release is available for deployment. - **Failed**: An asynchronous publish operation has failed. - **Processing**: An asynchronous publish operation has not yet completed. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - *, - release: str = None, - description: str = None, - environment_references: List['EnvironmentReference'] = None, - content: 'ReleaseContent' = None, - status: str = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Release object. @@ -7010,23 +7078,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Release': """Initialize a Release object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'environment_references' in _dict: + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: args['environment_references'] = [ EnvironmentReference.from_dict(v) - for v in _dict.get('environment_references') + for v in environment_references ] - if 'content' in _dict: - args['content'] = ReleaseContent.from_dict(_dict.get('content')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -7088,23 +7157,27 @@ class StatusEnum(str, Enum): - **Failed**: An asynchronous publish operation has failed. - **Processing**: An asynchronous publish operation has not yet completed. """ + AVAILABLE = 'Available' FAILED = 'Failed' PROCESSING = 'Processing' -class ReleaseCollection(): +class ReleaseCollection: """ ReleaseCollection. - :attr List[Release] releases: An array of objects describing the releases + :param List[Release] releases: An array of objects describing the releases associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, releases: List['Release'], - pagination: 'Pagination') -> None: + def __init__( + self, + releases: List['Release'], + pagination: 'Pagination', + ) -> None: """ Initialize a ReleaseCollection object. @@ -7120,16 +7193,14 @@ def __init__(self, releases: List['Release'], def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': """Initialize a ReleaseCollection object from a json dictionary.""" args = {} - if 'releases' in _dict: - args['releases'] = [ - Release.from_dict(v) for v in _dict.get('releases') - ] + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] else: raise ValueError( 'Required property \'releases\' not present in ReleaseCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ReleaseCollection JSON' @@ -7178,16 +7249,20 @@ def __ne__(self, other: 'ReleaseCollection') -> bool: return not self == other -class ReleaseContent(): +class ReleaseContent: """ An object identifying the versionable content objects (such as skill snapshots) that are included in the release. - :attr List[ReleaseSkill] skills: (optional) The skill snapshots that are + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are included in the release. """ - def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: + def __init__( + self, + *, + skills: Optional[List['ReleaseSkill']] = None, + ) -> None: """ Initialize a ReleaseContent object. @@ -7198,10 +7273,8 @@ def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ReleaseContent': """Initialize a ReleaseContent object from a json dictionary.""" args = {} - if 'skills' in _dict: - args['skills'] = [ - ReleaseSkill.from_dict(v) for v in _dict.get('skills') - ] + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] return cls(**args) @classmethod @@ -7241,23 +7314,25 @@ def __ne__(self, other: 'ReleaseContent') -> bool: return not self == other -class ReleaseSkill(): +class ReleaseSkill: """ ReleaseSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr str snapshot: (optional) The name of the skill snapshot that is saved as + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as part of the release (for example, `draft` or `1`). """ - def __init__(self, - skill_id: str, - *, - type: str = None, - snapshot: str = None) -> None: - """ - Initialize a ReleaseSkill object. + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + snapshot: Optional[str] = None, + ) -> None: + """ + Initialize a ReleaseSkill object. :param str skill_id: The skill ID of the skill. :param str type: (optional) The type of the skill. @@ -7272,16 +7347,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': """Initialize a ReleaseSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in ReleaseSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot return cls(**args) @classmethod @@ -7322,29 +7397,32 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class RequestAnalytics(): +class RequestAnalytics: """ An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. - :attr str browser: (optional) The browser that was used to send the message that - triggered the event. - :attr str device: (optional) The type of device that was used to send the - message that triggered the event. - :attr str page_url: (optional) The URL of the web page that was used to send the + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. """ - def __init__(self, - *, - browser: str = None, - device: str = None, - page_url: str = None) -> None: + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: """ Initialize a RequestAnalytics object. @@ -7363,12 +7441,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': """Initialize a RequestAnalytics object from a json dictionary.""" args = {} - if 'browser' in _dict: - args['browser'] = _dict.get('browser') - if 'device' in _dict: - args['device'] = _dict.get('device') - if 'pageUrl' in _dict: - args['page_url'] = _dict.get('pageUrl') + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url return cls(**args) @classmethod @@ -7406,14 +7484,18 @@ def __ne__(self, other: 'RequestAnalytics') -> bool: return not self == other -class ResponseGenericChannel(): +class ResponseGenericChannel: """ ResponseGenericChannel. - :attr str channel: (optional) A channel for which the response is intended. + :param str channel: (optional) A channel for which the response is intended. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: """ Initialize a ResponseGenericChannel object. @@ -7426,8 +7508,8 @@ def __init__(self, *, channel: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod @@ -7461,53 +7543,55 @@ def __ne__(self, other: 'ResponseGenericChannel') -> bool: return not self == other -class RuntimeEntity(): +class RuntimeEntity: """ The entity value that was recognized in the user input. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity + :param str value: The term in the input text that was recognized as an entity value. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object + :param RuntimeEntityInterpretation interpretation: (optional) An object containing detailed information about the entity recognized in the user input. This property is included only if the new system entities are enabled for the skill. For more information about how the new system entities are interpreted, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of possible alternative values that the user might have intended instead of the value returned in the **value** property. This property is returned only for `@sys-time` and `@sys-date` entities when the user's input is ambiguous. This property is included only if the new system entities are enabled for the skill. - :attr RuntimeEntityRole role: (optional) An object describing the role played by - a system entity that is specifies the beginning or end of a range recognized in - the user input. This property is included only if the new system entities are + :param RuntimeEntityRole role: (optional) An object describing the role played + by a system entity that is specifies the beginning or end of a range recognized + in the user input. This property is included only if the new system entities are enabled for the skill. - :attr str skill: (optional) The skill that recognized the entity value. + :param str skill: (optional) The skill that recognized the entity value. Currently, the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. This property is present only if the assistant has both a dialog skill and an action skill. """ - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None, - skill: str = None) -> None: + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntity object. @@ -7518,7 +7602,7 @@ def __init__(self, offsets that indicate where the detected entity values begin and end in the input text. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -7559,37 +7643,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(v) for v in _dict.get('groups') - ] - if 'interpretation' in _dict: + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) - for v in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) for v in alternatives ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill return cls(**args) @classmethod @@ -7657,24 +7738,29 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other -class RuntimeEntityAlternative(): +class RuntimeEntityAlternative: """ An alternative value for the recognized entity. - :attr str value: (optional) The entity value that was recognized in the user + :param str value: (optional) The entity value that was recognized in the user input. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeEntityAlternative object. :param str value: (optional) The entity value that was recognized in the user input. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. """ self.value = value self.confidence = confidence @@ -7683,10 +7769,10 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -7722,108 +7808,110 @@ def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: return not self == other -class RuntimeEntityInterpretation(): +class RuntimeEntityInterpretation: """ RuntimeEntityInterpretation. - :attr str calendar_type: (optional) The calendar used to represent a recognized + :param str calendar_type: (optional) The calendar used to represent a recognized date (for example, `Gregorian`). - :attr str datetime_link: (optional) A unique identifier used to associate a + :param str datetime_link: (optional) A unique identifier used to associate a recognized time and date. If the user input contains a date and time that are mentioned together (for example, `Today at 5`, the same **datetime_link** value is returned for both the `@sys-date` and `@sys-time` entities). - :attr str festival: (optional) A locale-specific holiday name (such as + :param str festival: (optional) A locale-specific holiday name (such as `thanksgiving` or `christmas`). This property is included when a `@sys-date` entity is recognized based on a holiday name in the user input. - :attr str granularity: (optional) The precision or duration of a time range + :param str granularity: (optional) The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - :attr str range_link: (optional) A unique identifier used to associate multiple + :param str range_link: (optional) A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are recognized as a range of values in the user's input (for example, `from July 4 until July 14` or `from 20 to 25`). - :attr str range_modifier: (optional) The word in the user input that indicates + :param str range_modifier: (optional) The word in the user input that indicates that a `sys-date` or `sys-time` entity is part of an implied range where only one date or time is specified (for example, `since` or `until`). - :attr float relative_day: (optional) A recognized mention of a relative day, + :param float relative_day: (optional) A recognized mention of a relative day, represented numerically as an offset from the current date (for example, `-1` for `yesterday` or `10` for `in ten days`). - :attr float relative_month: (optional) A recognized mention of a relative month, - represented numerically as an offset from the current month (for example, `1` - for `next month` or `-3` for `three months ago`). - :attr float relative_week: (optional) A recognized mention of a relative week, + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for example, + `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative week, represented numerically as an offset from the current week (for example, `2` for `in two weeks` or `-1` for `last week). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current + :param float relative_weekend: (optional) A recognized mention of a relative + date range for a weekend, represented numerically as an offset from the current weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :attr float relative_year: (optional) A recognized mention of a relative year, + :param float relative_year: (optional) A recognized mention of a relative year, represented numerically as an offset from the current year (for example, `1` for `next year` or `-5` for `five years ago`). - :attr float specific_day: (optional) A recognized mention of a specific date, + :param float specific_day: (optional) A recognized mention of a specific date, represented numerically as the date within the month (for example, `30` for `June 30`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific + :param str specific_day_of_week: (optional) A recognized mention of a specific day of the week as a lowercase string (for example, `monday`). - :attr float specific_month: (optional) A recognized mention of a specific month, - represented numerically (for example, `7` for `July`). - :attr float specific_quarter: (optional) A recognized mention of a specific + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third quarter`). - :attr float specific_year: (optional) A recognized mention of a specific year + :param float specific_year: (optional) A recognized mention of a specific year (for example, `2016`). - :attr float numeric_value: (optional) A recognized numeric value, represented as - an integer or double. - :attr str subtype: (optional) The type of numeric value recognized in the user + :param float numeric_value: (optional) A recognized numeric value, represented + as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the user input (`integer` or `rational`). - :attr str part_of_day: (optional) A recognized term for a time that was + :param str part_of_day: (optional) A recognized term for a time that was mentioned as a part of the day in the user's input (for example, `morning` or `afternoon`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, + :param float relative_hour: (optional) A recognized mention of a relative hour, represented numerically as an offset from the current hour (for example, `3` for `in three hours` or `-1` for `an hour ago`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time (for example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as + :param float specific_hour: (optional) A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.). - :attr float specific_minute: (optional) A recognized specific minute mentioned + :param float specific_minute: (optional) A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.). - :attr float specific_second: (optional) A recognized specific second mentioned + :param float specific_second: (optional) A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - :attr str timezone: (optional) A recognized time zone mentioned as part of a + :param str timezone: (optional) A recognized time zone mentioned as part of a time value (for example, `EST`). """ - def __init__(self, - *, - calendar_type: str = None, - datetime_link: str = None, - festival: str = None, - granularity: str = None, - range_link: str = None, - range_modifier: str = None, - relative_day: float = None, - relative_month: float = None, - relative_week: float = None, - relative_weekend: float = None, - relative_year: float = None, - specific_day: float = None, - specific_day_of_week: str = None, - specific_month: float = None, - specific_quarter: float = None, - specific_year: float = None, - numeric_value: float = None, - subtype: str = None, - part_of_day: str = None, - relative_hour: float = None, - relative_minute: float = None, - relative_second: float = None, - specific_hour: float = None, - specific_minute: float = None, - specific_second: float = None, - timezone: str = None) -> None: + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityInterpretation object. @@ -7932,58 +8020,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" args = {} - if 'calendar_type' in _dict: - args['calendar_type'] = _dict.get('calendar_type') - if 'datetime_link' in _dict: - args['datetime_link'] = _dict.get('datetime_link') - if 'festival' in _dict: - args['festival'] = _dict.get('festival') - if 'granularity' in _dict: - args['granularity'] = _dict.get('granularity') - if 'range_link' in _dict: - args['range_link'] = _dict.get('range_link') - if 'range_modifier' in _dict: - args['range_modifier'] = _dict.get('range_modifier') - if 'relative_day' in _dict: - args['relative_day'] = _dict.get('relative_day') - if 'relative_month' in _dict: - args['relative_month'] = _dict.get('relative_month') - if 'relative_week' in _dict: - args['relative_week'] = _dict.get('relative_week') - if 'relative_weekend' in _dict: - args['relative_weekend'] = _dict.get('relative_weekend') - if 'relative_year' in _dict: - args['relative_year'] = _dict.get('relative_year') - if 'specific_day' in _dict: - args['specific_day'] = _dict.get('specific_day') - if 'specific_day_of_week' in _dict: - args['specific_day_of_week'] = _dict.get('specific_day_of_week') - if 'specific_month' in _dict: - args['specific_month'] = _dict.get('specific_month') - if 'specific_quarter' in _dict: - args['specific_quarter'] = _dict.get('specific_quarter') - if 'specific_year' in _dict: - args['specific_year'] = _dict.get('specific_year') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') - if 'part_of_day' in _dict: - args['part_of_day'] = _dict.get('part_of_day') - if 'relative_hour' in _dict: - args['relative_hour'] = _dict.get('relative_hour') - if 'relative_minute' in _dict: - args['relative_minute'] = _dict.get('relative_minute') - if 'relative_second' in _dict: - args['relative_second'] = _dict.get('relative_second') - if 'specific_hour' in _dict: - args['specific_hour'] = _dict.get('specific_hour') - if 'specific_minute' in _dict: - args['specific_minute'] = _dict.get('specific_minute') - if 'specific_second' in _dict: - args['specific_second'] = _dict.get('specific_second') - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone return cls(**args) @classmethod @@ -8078,6 +8167,7 @@ class GranularityEnum(str, Enum): The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. """ + DAY = 'day' FORTNIGHT = 'fortnight' HOUR = 'hour' @@ -8091,16 +8181,20 @@ class GranularityEnum(str, Enum): YEAR = 'year' -class RuntimeEntityRole(): +class RuntimeEntityRole: """ An object describing the role played by a system entity that is specifies the beginning or end of a range recognized in the user input. This property is included only if the new system entities are enabled for the skill. - :attr str type: (optional) The relationship of the entity to the range. + :param str type: (optional) The relationship of the entity to the range. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityRole object. @@ -8112,8 +8206,8 @@ def __init__(self, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -8150,6 +8244,7 @@ class TypeEnum(str, Enum): """ The relationship of the entity to the range. """ + DATE_FROM = 'date_from' DATE_TO = 'date_to' NUMBER_FROM = 'number_from' @@ -8158,34 +8253,35 @@ class TypeEnum(str, Enum): TIME_TO = 'time_to' -class RuntimeIntent(): +class RuntimeIntent: """ An intent identified in the user input. - :attr str intent: The name of the recognized intent. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents confidence in the intent. If you are specifying an intent as part of a request, but you do not have a calculated confidence value, specify `1`. - :attr str skill: (optional) The skill that identified the intent. Currently, the - only possible values are `main skill` for the dialog skill (if enabled) and + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. This property is present only if the assistant has both a dialog skill and an action skill. """ - def __init__(self, - intent: str, - *, - confidence: float = None, - skill: str = None) -> None: + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part - of a request, but you do not have a calculated confidence value, specify - `1`. + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. :param str skill: (optional) The skill that identified the intent. Currently, the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. @@ -8200,16 +8296,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill return cls(**args) @classmethod @@ -8247,13 +8343,13 @@ def __ne__(self, other: 'RuntimeIntent') -> bool: return not self == other -class RuntimeResponseGeneric(): +class RuntimeResponseGeneric: """ RuntimeResponseGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -8282,24 +8378,22 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) raise Exception(msg) @classmethod @@ -8342,28 +8436,28 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class SearchResult(): +class SearchResult: """ SearchResult. - :attr str id: The unique identifier of the document in the Discovery service + :param str id: The unique identifier of the document in the Discovery service collection. This property is included in responses from search skills, which are available only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result + :param SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken + :param str body: (optional) A description of the search result. This is taken from an abstract, summary, or highlight field in the Discovery service response, as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + :param List[SearchResultAnswer] answers: (optional) An array specifying segments of text within the result that were identified as direct answers to the search query. Currently, only the single answer with the highest confidence (if any) is returned. @@ -8373,15 +8467,17 @@ class SearchResult(): - Answer finding is not supported on IBM Cloud Pak for Data. """ - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: """ Initialize a SearchResult object. @@ -8423,31 +8519,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResult': """Initialize a SearchResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) else: raise ValueError( 'Required property \'result_metadata\' not present in SearchResult JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(v) for v in _dict.get('answers') - ] + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] return cls(**args) @classmethod @@ -8506,17 +8599,21 @@ def __ne__(self, other: 'SearchResult') -> bool: return not self == other -class SearchResultAnswer(): +class SearchResultAnswer: """ An object specifing a segment of text that was identified as a direct answer to the search query. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the Discovery service. """ - def __init__(self, text: str, confidence: float) -> None: + def __init__( + self, + text: str, + confidence: float, + ) -> None: """ Initialize a SearchResultAnswer object. @@ -8531,14 +8628,14 @@ def __init__(self, text: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': """Initialize a SearchResultAnswer object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in SearchResultAnswer JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in SearchResultAnswer JSON' @@ -8578,30 +8675,32 @@ def __ne__(self, other: 'SearchResultAnswer') -> bool: return not self == other -class SearchResultHighlight(): +class SearchResultHighlight: """ An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. - :attr List[str] body: (optional) An array of strings containing segments taken + :param List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken + :param List[str] title: (optional) An array of strings containing segments taken from title text in the search results, with query-matching substrings highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken + :param List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. """ # The set of defined properties for the class _properties = frozenset(['body', 'title', 'url']) - def __init__(self, - *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs, + ) -> None: """ Initialize a SearchResultHighlight object. @@ -8626,12 +8725,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -8699,21 +8798,23 @@ def __ne__(self, other: 'SearchResultHighlight') -> bool: return not self == other -class SearchResultMetadata(): +class SearchResultMetadata: """ An object containing search result metadata from the Discovery service. - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. """ - def __init__(self, - *, - confidence: float = None, - score: float = None) -> None: + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a SearchResultMetadata object. @@ -8730,10 +8831,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -8769,21 +8870,26 @@ def __ne__(self, other: 'SearchResultMetadata') -> bool: return not self == other -class SearchSettings(): +class SearchSettings: """ An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. - :attr SearchSettingsDiscovery discovery: Configuration settings for the Watson + :param SearchSettingsDiscovery discovery: Configuration settings for the Watson Discovery service instance used by the search integration. - :attr SearchSettingsMessages messages: The messages included with responses from - the search integration. - :attr SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in the Watson Discovery collection and properties in the search response. """ - def __init__(self, discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping') -> None: + def __init__( + self, + discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + ) -> None: """ Initialize a SearchSettings object. @@ -8803,23 +8909,21 @@ def __init__(self, discovery: 'SearchSettingsDiscovery', def from_dict(cls, _dict: Dict) -> 'SearchSettings': """Initialize a SearchSettings object from a json dictionary.""" args = {} - if 'discovery' in _dict: - args['discovery'] = SearchSettingsDiscovery.from_dict( - _dict.get('discovery')) + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) else: raise ValueError( 'Required property \'discovery\' not present in SearchSettings JSON' ) - if 'messages' in _dict: - args['messages'] = SearchSettingsMessages.from_dict( - _dict.get('messages')) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) else: raise ValueError( 'Required property \'messages\' not present in SearchSettings JSON' ) - if 'schema_mapping' in _dict: + if (schema_mapping := _dict.get('schema_mapping')) is not None: args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - _dict.get('schema_mapping')) + schema_mapping) else: raise ValueError( 'Required property \'schema_mapping\' not present in SearchSettings JSON' @@ -8870,48 +8974,50 @@ def __ne__(self, other: 'SearchSettings') -> bool: return not self == other -class SearchSettingsDiscovery(): +class SearchSettingsDiscovery: """ Configuration settings for the Watson Discovery service instance used by the search integration. - :attr str instance_id: The ID for the Watson Discovery service instance. - :attr str project_id: The ID for the Watson Discovery project. - :attr str url: The URL for the Watson Discovery service instance. - :attr int max_primary_results: (optional) The maximum number of primary results + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results to include in the response. - :attr int max_total_results: (optional) The maximum total number of primary and + :param int max_total_results: (optional) The maximum total number of primary and additional results to include in the response. - :attr float confidence_threshold: (optional) The minimum confidence threshold + :param float confidence_threshold: (optional) The minimum confidence threshold for included results. Any results with a confidence below this threshold will be discarded. - :attr bool highlight: (optional) Whether to include the most relevant passages + :param bool highlight: (optional) Whether to include the most relevant passages of text in the **highlight** property of each result. - :attr bool find_answers: (optional) Whether to use the answer finding feature to - emphasize answers within highlighted passages. This property is ignored if + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if **highlight**=`false`. **Notes:** - Answer finding is available only if the search skill is connected to a Discovery v2 service instance. - Answer finding is not supported on IBM Cloud Pak for Data. - :attr SearchSettingsDiscoveryAuthentication authentication: Authentication + :param SearchSettingsDiscoveryAuthentication authentication: Authentication information for the Watson Discovery service. For more information, see the [Watson Discovery documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). **Note:** You must specify either **basic** or **bearer**, but not both. """ - def __init__(self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', - *, - max_primary_results: int = None, - max_total_results: int = None, - confidence_threshold: float = None, - highlight: bool = None, - find_answers: bool = None) -> None: + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: """ Initialize a SearchSettingsDiscovery object. @@ -8954,38 +9060,40 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': """Initialize a SearchSettingsDiscovery object from a json dictionary.""" args = {} - if 'instance_id' in _dict: - args['instance_id'] = _dict.get('instance_id') + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id else: raise ValueError( 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' ) - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id else: raise ValueError( 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' ) - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SearchSettingsDiscovery JSON' ) - if 'max_primary_results' in _dict: - args['max_primary_results'] = _dict.get('max_primary_results') - if 'max_total_results' in _dict: - args['max_total_results'] = _dict.get('max_total_results') - if 'confidence_threshold' in _dict: - args['confidence_threshold'] = _dict.get('confidence_threshold') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'authentication' in _dict: + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: args[ 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - _dict.get('authentication')) + authentication) else: raise ValueError( 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' @@ -9046,21 +9154,26 @@ def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: return not self == other -class SearchSettingsDiscoveryAuthentication(): +class SearchSettingsDiscoveryAuthentication: """ Authentication information for the Watson Discovery service. For more information, see the [Watson Discovery documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). **Note:** You must specify either **basic** or **bearer**, but not both. - :attr str basic: (optional) The HTTP basic authentication credentials for Watson - Discovery. Specify your Watson Discovery API key in the format + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format `apikey:{apikey}`. - :attr str bearer: (optional) The authentication bearer token for Watson + :param str bearer: (optional) The authentication bearer token for Watson Discovery. """ - def __init__(self, *, basic: str = None, bearer: str = None) -> None: + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: """ Initialize a SearchSettingsDiscoveryAuthentication object. @@ -9077,10 +9190,10 @@ def __init__(self, *, basic: str = None, bearer: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" args = {} - if 'basic' in _dict: - args['basic'] = _dict.get('basic') - if 'bearer' in _dict: - args['bearer'] = _dict.get('bearer') + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer return cls(**args) @classmethod @@ -9116,18 +9229,24 @@ def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: return not self == other -class SearchSettingsMessages(): +class SearchSettingsMessages: """ The messages included with responses from the search integration. - :attr str success: The message to include in the response to a successful query. - :attr str error: The message to include in the response when the query + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query encounters an error. - :attr str no_result: The message to include in the response when there is no + :param str no_result: The message to include in the response when there is no result from the query. """ - def __init__(self, success: str, error: str, no_result: str) -> None: + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: """ Initialize a SearchSettingsMessages object. @@ -9146,20 +9265,20 @@ def __init__(self, success: str, error: str, no_result: str) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': """Initialize a SearchSettingsMessages object from a json dictionary.""" args = {} - if 'success' in _dict: - args['success'] = _dict.get('success') + if (success := _dict.get('success')) is not None: + args['success'] = success else: raise ValueError( 'Required property \'success\' not present in SearchSettingsMessages JSON' ) - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error else: raise ValueError( 'Required property \'error\' not present in SearchSettingsMessages JSON' ) - if 'no_result' in _dict: - args['no_result'] = _dict.get('no_result') + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result else: raise ValueError( 'Required property \'no_result\' not present in SearchSettingsMessages JSON' @@ -9201,20 +9320,25 @@ def __ne__(self, other: 'SearchSettingsMessages') -> bool: return not self == other -class SearchSettingsSchemaMapping(): +class SearchSettingsSchemaMapping: """ The mapping between fields in the Watson Discovery collection and properties in the search response. - :attr str url: The field in the collection to map to the **url** property of the - response. - :attr str body: The field in the collection to map to the **body** property in + :param str url: The field in the collection to map to the **url** property of the response. - :attr str title: The field in the collection to map to the **title** property + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property for the schema. """ - def __init__(self, url: str, body: str, title: str) -> None: + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: """ Initialize a SearchSettingsSchemaMapping object. @@ -9233,20 +9357,20 @@ def __init__(self, url: str, body: str, title: str) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') + if (body := _dict.get('body')) is not None: + args['body'] = body else: raise ValueError( 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' @@ -9288,21 +9412,23 @@ def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: return not self == other -class SearchSkillWarning(): +class SearchSkillWarning: """ A warning describing an error in the search skill configuration. - :attr str code: (optional) The error code. - :attr str path: (optional) The location of the error in the search skill + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill configuration object. - :attr str message: (optional) The error message. + :param str message: (optional) The error message. """ - def __init__(self, - *, - code: str = None, - path: str = None, - message: str = None) -> None: + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: """ Initialize a SearchSkillWarning object. @@ -9319,12 +9445,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': """Initialize a SearchSkillWarning object from a json dictionary.""" args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') - if 'path' in _dict: - args['path'] = _dict.get('path') - if 'message' in _dict: - args['message'] = _dict.get('message') + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -9362,14 +9488,17 @@ def __ne__(self, other: 'SearchSkillWarning') -> bool: return not self == other -class SessionResponse(): +class SessionResponse: """ SessionResponse. - :attr str session_id: The session ID. + :param str session_id: The session ID. """ - def __init__(self, session_id: str) -> None: + def __init__( + self, + session_id: str, + ) -> None: """ Initialize a SessionResponse object. @@ -9381,8 +9510,8 @@ def __init__(self, session_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SessionResponse': """Initialize a SessionResponse object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id else: raise ValueError( 'Required property \'session_id\' not present in SessionResponse JSON' @@ -9420,69 +9549,73 @@ def __ne__(self, other: 'SessionResponse') -> bool: return not self == other -class Skill(): +class Skill: """ Skill. - :attr str name: (optional) The name of the skill. This string cannot contain + :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the skill. This string + :param str description: (optional) The description of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr dict workspace: (optional) An object containing the conversational content - of an action or dialog skill. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str status: (optional) The current status of the skill: + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: - **Available**: The skill is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - **Non Existent**: The skill does not exist. - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr dict dialog_settings: (optional) For internal use only. - :attr str assistant_id: (optional) The unique identifier of the assistant the + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the skill is associated with. - :attr str workspace_id: (optional) The unique identifier of the workspace that + :param str workspace_id: (optional) The unique identifier of the workspace that contains the skill content. Included only for action and dialog skills. - :attr str environment_id: (optional) The unique identifier of the environment + :param str environment_id: (optional) The unique identifier of the environment where the skill is defined. For action and dialog skills, this is always the draft environment. - :attr bool valid: (optional) Whether the skill is structurally valid. - :attr str next_snapshot_version: (optional) The name that will be given to the + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr SearchSettings search_settings: (optional) An object describing the search - skill configuration. - :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. - :attr str language: The language of the skill. - :attr str type: The type of skill. - """ - - def __init__(self, - language: str, - type: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - skill_id: str = None, - status: str = None, - status_errors: List['StatusError'] = None, - status_description: str = None, - dialog_settings: dict = None, - assistant_id: str = None, - workspace_id: str = None, - environment_id: str = None, - valid: bool = None, - next_snapshot_version: str = None, - search_settings: 'SearchSettings' = None, - warnings: List['SearchSkillWarning'] = None) -> None: + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: """ Initialize a Skill object. @@ -9497,6 +9630,8 @@ def __init__(self, :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ self.name = name self.description = description @@ -9520,48 +9655,48 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Skill': """Initialize a Skill object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace' in _dict: - args['workspace'] = _dict.get('workspace') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') + StatusError.from_dict(v) for v in status_errors ] - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'dialog_settings' in _dict: - args['dialog_settings'] = _dict.get('dialog_settings') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'valid' in _dict: - args['valid'] = _dict.get('valid') - if 'next_snapshot_version' in _dict: - args['next_snapshot_version'] = _dict.get('next_snapshot_version') - if 'search_settings' in _dict: - args['search_settings'] = SearchSettings.from_dict( - _dict.get('search_settings')) - if 'warnings' in _dict: + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + SearchSkillWarning.from_dict(v) for v in warnings ] - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Skill JSON') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in Skill JSON') @@ -9663,6 +9798,7 @@ class StatusEnum(str, Enum): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -9674,74 +9810,79 @@ class TypeEnum(str, Enum): """ The type of skill. """ + ACTION = 'action' DIALOG = 'dialog' SEARCH = 'search' -class SkillImport(): +class SkillImport: """ SkillImport. - :attr str name: (optional) The name of the skill. This string cannot contain + :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the skill. This string + :param str description: (optional) The description of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr dict workspace: (optional) An object containing the conversational content - of an action or dialog skill. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str status: (optional) The current status of the skill: + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: - **Available**: The skill is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - **Non Existent**: The skill does not exist. - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr dict dialog_settings: (optional) For internal use only. - :attr str assistant_id: (optional) The unique identifier of the assistant the + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the skill is associated with. - :attr str workspace_id: (optional) The unique identifier of the workspace that + :param str workspace_id: (optional) The unique identifier of the workspace that contains the skill content. Included only for action and dialog skills. - :attr str environment_id: (optional) The unique identifier of the environment + :param str environment_id: (optional) The unique identifier of the environment where the skill is defined. For action and dialog skills, this is always the draft environment. - :attr bool valid: (optional) Whether the skill is structurally valid. - :attr str next_snapshot_version: (optional) The name that will be given to the + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr SearchSettings search_settings: (optional) An object describing the search - skill configuration. - :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. - :attr str language: The language of the skill. - :attr str type: The type of skill. - """ - - def __init__(self, - language: str, - type: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - skill_id: str = None, - status: str = None, - status_errors: List['StatusError'] = None, - status_description: str = None, - dialog_settings: dict = None, - assistant_id: str = None, - workspace_id: str = None, - environment_id: str = None, - valid: bool = None, - next_snapshot_version: str = None, - search_settings: 'SearchSettings' = None, - warnings: List['SearchSkillWarning'] = None) -> None: + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: """ Initialize a SkillImport object. @@ -9756,6 +9897,8 @@ def __init__(self, :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ self.name = name self.description = description @@ -9779,49 +9922,49 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SkillImport': """Initialize a SkillImport object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace' in _dict: - args['workspace'] = _dict.get('workspace') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') + StatusError.from_dict(v) for v in status_errors ] - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'dialog_settings' in _dict: - args['dialog_settings'] = _dict.get('dialog_settings') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'valid' in _dict: - args['valid'] = _dict.get('valid') - if 'next_snapshot_version' in _dict: - args['next_snapshot_version'] = _dict.get('next_snapshot_version') - if 'search_settings' in _dict: - args['search_settings'] = SearchSettings.from_dict( - _dict.get('search_settings')) - if 'warnings' in _dict: + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + SearchSkillWarning.from_dict(v) for v in warnings ] - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in SkillImport JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in SkillImport JSON') @@ -9923,6 +10066,7 @@ class StatusEnum(str, Enum): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -9934,85 +10078,1020 @@ class TypeEnum(str, Enum): """ The type of skill. """ + ACTION = 'action' DIALOG = 'dialog' - SEARCH = 'search' -class SkillsAsyncRequestStatus(): +class SkillsAsyncRequestStatus: """ SkillsAsyncRequestStatus. - :attr str assistant_id: (optional) The assistant ID of the assistant. - :attr str status: (optional) The current status of the asynchronous operation: + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: - `Available`: An asynchronous export is available. - `Completed`: An asynchronous import operation has completed successfully. - `Failed`: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - `Processing`: An asynchronous operation has not yet completed. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. """ - def __init__(self, - *, - assistant_id: str = None, - status: str = None, - status_description: str = None, - status_errors: List['StatusError'] = None) -> None: + def __init__( + self, + *, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + ) -> None: """ Initialize a SkillsAsyncRequestStatus object. """ - self.assistant_id = assistant_id - self.status = status - self.status_description = status_description - self.status_errors = status_errors + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + args = {} + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsAsyncRequestStatus object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + """ + + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class SkillsExport: + """ + SkillsExport. + + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. + """ + + def __init__( + self, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', + ) -> None: + """ + Initialize a SkillsExport object. + + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + """ + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" + args = {} + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] + else: + raise ValueError( + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsExport object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsExport object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatefulMessageResponse: + """ + A response from the watsonx Assistant service. + + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + """ + + def __init__( + self, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + ) -> None: + """ + Initialize a StatefulMessageResponse object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + """ + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in StatefulMessageResponse JSON' + ) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' + ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatefulMessageResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatefulMessageResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatefulMessageResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatefulMessageResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContext: + """ + StatelessMessageContext. + + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__( + self, + *, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: + """ + Initialize a StatelessMessageContext object. + + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" + args = {} + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContext object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContext object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContext') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextGlobal: + """ + Session context data that is shared by all skills used by the assistant. + + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. + """ + + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: + """ + Initialize a StatelessMessageContextGlobal object. + + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. + """ + self.system = system + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + args = {} + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextGlobal object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextSkills: + """ + Context data specific to particular skills used by the assistant. + + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. + """ + + def __init__( + self, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, + ) -> None: + """ + Initialize a StatelessMessageContextSkills object. + + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + args = {} + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextSkills object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextSkillsActionsSkill: + """ + Context variables that are used by the action skill. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. + """ + + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, + ) -> None: + """ + Initialize a StatelessMessageContextSkillsActionsSkill object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" + args = {} + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageInput: + """ + An input object that includes the input text. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, + ) -> None: + """ + Initialize a StatelessMessageInput object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" + args = {} + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageInput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageInput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + + +class StatelessMessageInputOptions: + """ + Optional properties that control how the assistant responds. + + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + ) -> None: + """ + Initialize a StatelessMessageInputOptions object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" args = {} - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'status_errors' in _dict: - args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') - ] + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -10020,102 +11099,137 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsAsyncRequestStatus object.""" + """Return a `str` version of this StatelessMessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - """ - AVAILABLE = 'Available' - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' - -class SkillsExport(): +class StatelessMessageResponse: """ - SkillsExport. + A stateless response from the watsonx Assistant service. - :attr List[Skill] assistant_skills: An array of objects describing the skills - for the assistant. Included in responses only if **status**=`Available`. - :attr AssistantState assistant_state: Status information about the skills for - the assistant. Included in responses only if **status**=`Available`. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ - def __init__(self, assistant_skills: List['Skill'], - assistant_state: 'AssistantState') -> None: + def __init__( + self, + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, + ) -> None: """ - Initialize a SkillsExport object. + Initialize a StatelessMessageResponse object. - :param List[Skill] assistant_skills: An array of objects describing the - skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.assistant_skills = assistant_skills - self.assistant_state = assistant_state + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsExport': - """Initialize a SkillsExport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" args = {} - if 'assistant_skills' in _dict: - args['assistant_skills'] = [ - Skill.from_dict(v) for v in _dict.get('assistant_skills') - ] + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'assistant_skills\' not present in SkillsExport JSON' + 'Required property \'output\' not present in StatelessMessageResponse JSON' ) - if 'assistant_state' in _dict: - args['assistant_state'] = AssistantState.from_dict( - _dict.get('assistant_state')) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) else: raise ValueError( - 'Required property \'assistant_state\' not present in SkillsExport JSON' + 'Required property \'context\' not present in StatelessMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsExport object from a json dictionary.""" + """Initialize a StatelessMessageResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'assistant_skills') and self.assistant_skills is not None: - assistant_skills_list = [] - for v in self.assistant_skills: - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, - 'assistant_state') and self.assistant_state is not None: - if isinstance(self.assistant_state, dict): - _dict['assistant_state'] = self.assistant_state + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['assistant_state'] = self.assistant_state.to_dict() + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -10123,29 +11237,33 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsExport object.""" + """Return a `str` version of this StatelessMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsExport') -> bool: + def __eq__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SkillsExport') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatusError(): +class StatusError: """ An object describing an error that occurred during processing of an asynchronous operation. - :attr str message: (optional) The text of the error message. + :param str message: (optional) The text of the error message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a StatusError object. @@ -10157,8 +11275,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'StatusError': """Initialize a StatusError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10192,23 +11310,25 @@ def __ne__(self, other: 'StatusError') -> bool: return not self == other -class TurnEventActionSource(): +class TurnEventActionSource: """ TurnEventActionSource. - :attr str type: (optional) The type of turn event. - :attr str action: (optional) An action that was visited during processing of the - message. - :attr str action_title: (optional) The title of the action. - :attr str condition: (optional) The condition that triggered the dialog node. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, - *, - type: str = None, - action: str = None, - action_title: str = None, - condition: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ Initialize a TurnEventActionSource object. @@ -10228,14 +11348,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'action' in _dict: - args['action'] = _dict.get('action') - if 'action_title' in _dict: - args['action_title'] = _dict.get('action_title') - if 'condition' in _dict: - args['condition'] = _dict.get('condition') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod @@ -10278,25 +11398,28 @@ class TypeEnum(str, Enum): """ The type of turn event. """ + ACTION = 'action' -class TurnEventCalloutCallout(): +class TurnEventCalloutCallout: """ TurnEventCalloutCallout. - :attr str type: (optional) The type of callout. Currently, the only supported + :param str type: (optional) The type of callout. Currently, the only supported value is `integration_interaction` (for calls to extensions). - :attr dict internal: (optional) For internal use only. - :attr str result_variable: (optional) The name of the variable where the callout - result is stored. + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. """ - def __init__(self, - *, - type: str = None, - internal: dict = None, - result_variable: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + ) -> None: """ Initialize a TurnEventCalloutCallout object. @@ -10314,12 +11437,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': """Initialize a TurnEventCalloutCallout object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'internal' in _dict: - args['internal'] = _dict.get('internal') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod @@ -10362,18 +11485,23 @@ class TypeEnum(str, Enum): The type of callout. Currently, the only supported value is `integration_interaction` (for calls to extensions). """ + INTEGRATION_INTERACTION = 'integration_interaction' -class TurnEventCalloutError(): +class TurnEventCalloutError: """ TurnEventCalloutError. - :attr str message: (optional) Any error message returned by a failed call to an + :param str message: (optional) Any error message returned by a failed call to an external service. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a TurnEventCalloutError object. @@ -10386,8 +11514,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10421,23 +11549,25 @@ def __ne__(self, other: 'TurnEventCalloutError') -> bool: return not self == other -class TurnEventNodeSource(): +class TurnEventNodeSource: """ TurnEventNodeSource. - :attr str type: (optional) The type of turn event. - :attr str dialog_node: (optional) A dialog node that was visited during + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str condition: (optional) The condition that triggered the dialog node. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, - *, - type: str = None, - dialog_node: str = None, - title: str = None, - condition: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ Initialize a TurnEventNodeSource object. @@ -10457,14 +11587,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': """Initialize a TurnEventNodeSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'condition' in _dict: - args['condition'] = _dict.get('condition') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod @@ -10507,18 +11637,23 @@ class TypeEnum(str, Enum): """ The type of turn event. """ + DIALOG_NODE = 'dialog_node' -class TurnEventSearchError(): +class TurnEventSearchError: """ TurnEventSearchError. - :attr str message: (optional) Any error message returned by a failed call to a + :param str message: (optional) Any error message returned by a failed call to a search skill. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a TurnEventSearchError object. @@ -10531,8 +11666,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10570,13 +11705,17 @@ class LogMessageSourceAction(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. """ - def __init__(self, type: str, action: str) -> None: + def __init__( + self, + type: str, + action: str, + ) -> None: """ Initialize a LogMessageSourceAction object. @@ -10593,14 +11732,14 @@ def __init__(self, type: str, action: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': """Initialize a LogMessageSourceAction object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceAction JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceAction JSON' @@ -10644,13 +11783,17 @@ class LogMessageSourceDialogNode(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str dialog_node: The unique identifier of the dialog node that generated + :param str dialog_node: The unique identifier of the dialog node that generated the error message. """ - def __init__(self, type: str, dialog_node: str) -> None: + def __init__( + self, + type: str, + dialog_node: str, + ) -> None: """ Initialize a LogMessageSourceDialogNode object. @@ -10667,14 +11810,14 @@ def __init__(self, type: str, dialog_node: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node else: raise ValueError( 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' @@ -10718,22 +11861,24 @@ class LogMessageSourceHandler(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. - :attr str step: (optional) The unique identifier of the step that generated the + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the error message. - :attr str handler: The unique identifier of the handler that generated the error - message. """ - def __init__(self, - type: str, - action: str, - handler: str, - *, - step: str = None) -> None: + def __init__( + self, + type: str, + action: str, + handler: str, + *, + step: Optional[str] = None, + ) -> None: """ Initialize a LogMessageSourceHandler object. @@ -10756,22 +11901,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceHandler JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceHandler JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'handler' in _dict: - args['handler'] = _dict.get('handler') + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler else: raise ValueError( 'Required property \'handler\' not present in LogMessageSourceHandler JSON' @@ -10819,15 +11964,20 @@ class LogMessageSourceStep(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. - :attr str step: The unique identifier of the step that generated the error + :param str step: The unique identifier of the step that generated the error message. """ - def __init__(self, type: str, action: str, step: str) -> None: + def __init__( + self, + type: str, + action: str, + step: str, + ) -> None: """ Initialize a LogMessageSourceStep object. @@ -10847,20 +11997,20 @@ def __init__(self, type: str, action: str, step: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceStep JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceStep JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') + if (step := _dict.get('step')) is not None: + args['step'] = step else: raise ValueError( 'Required property \'step\' not present in LogMessageSourceStep JSON' @@ -10907,25 +12057,27 @@ class MessageOutputDebugTurnEventTurnEventActionFinished( """ MessageOutputDebugTurnEventTurnEventActionFinished. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. - :attr str condition_type: (optional) The type of condition (if any) that is + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str reason: (optional) The reason the action finished processing. - :attr dict action_variables: (optional) The state of all action variables at the - time the action finished. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None, - condition_type: str = None, - reason: str = None, - action_variables: dict = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. @@ -10953,19 +12105,18 @@ def from_dict( ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'reason' in _dict: - args['reason'] = _dict.get('reason') - if 'action_variables' in _dict: - args['action_variables'] = _dict.get('action_variables') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod @@ -11021,6 +12172,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11029,6 +12181,7 @@ class ReasonEnum(str, Enum): """ The reason the action finished processing. """ + ALL_STEPS_DONE = 'all_steps_done' NO_STEPS_VISITED = 'no_steps_visited' ENDED_BY_STEP = 'ended_by_step' @@ -11042,25 +12195,27 @@ class MessageOutputDebugTurnEventTurnEventActionVisited( """ MessageOutputDebugTurnEventTurnEventActionVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. - :attr str condition_type: (optional) The type of condition (if any) that is + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str reason: (optional) The reason the action was visited. - :attr str result_variable: (optional) The variable where the result of the call + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call to the action is stored. Included only if **reason**=`subaction_return`. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None, - condition_type: str = None, - reason: str = None, - result_variable: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + result_variable: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. @@ -11089,19 +12244,18 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'reason' in _dict: - args['reason'] = _dict.get('reason') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod @@ -11157,6 +12311,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11165,6 +12320,7 @@ class ReasonEnum(str, Enum): """ The reason the action was visited. """ + INTENT = 'intent' INVOKE_SUBACTION = 'invoke_subaction' SUBACTION_RETURN = 'subaction_return' @@ -11180,18 +12336,20 @@ class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ MessageOutputDebugTurnEventTurnEventCallout. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr TurnEventCalloutCallout callout: (optional) - :attr TurnEventCalloutError error: (optional) + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - callout: 'TurnEventCalloutCallout' = None, - error: 'TurnEventCalloutError' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventCallout object. @@ -11211,16 +12369,14 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'callout' in _dict: - args['callout'] = TurnEventCalloutCallout.from_dict( - _dict.get('callout')) - if 'error' in _dict: - args['error'] = TurnEventCalloutError.from_dict(_dict.get('error')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod @@ -11276,17 +12432,19 @@ class MessageOutputDebugTurnEventTurnEventHandlerVisited( """ MessageOutputDebugTurnEventTurnEventHandlerVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. @@ -11306,13 +12464,12 @@ def from_dict( ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod @@ -11363,16 +12520,18 @@ class MessageOutputDebugTurnEventTurnEventNodeVisited( """ MessageOutputDebugTurnEventTurnEventNodeVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventNodeSource source: (optional) - :attr str reason: (optional) The reason the dialog node was visited. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventNodeSource' = None, - reason: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. @@ -11391,12 +12550,12 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventNodeSource.from_dict(_dict.get('source')) - if 'reason' in _dict: - args['reason'] = _dict.get('reason') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod @@ -11444,6 +12603,7 @@ class ReasonEnum(str, Enum): """ The reason the dialog node was visited. """ + WELCOME = 'welcome' BRANCH_START = 'branch_start' TOPIC_SWITCH = 'topic_switch' @@ -11456,16 +12616,18 @@ class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ MessageOutputDebugTurnEventTurnEventSearch. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr TurnEventSearchError error: (optional) + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - error: 'TurnEventSearchError' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + error: Optional['TurnEventSearchError'] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventSearch object. @@ -11483,13 +12645,12 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'error' in _dict: - args['error'] = TurnEventSearchError.from_dict(_dict.get('error')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod @@ -11540,24 +12701,26 @@ class MessageOutputDebugTurnEventTurnEventStepAnswered( """ MessageOutputDebugTurnEventTurnEventStepAnswered. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str condition_type: (optional) The type of condition (if any) that is + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str action_start_time: (optional) The time when the action started + :param str action_start_time: (optional) The time when the action started processing the message. - :attr bool prompted: (optional) Whether the step was answered in response to a + :param bool prompted: (optional) Whether the step was answered in response to a prompt from the assistant. If this property is `false`, the user provided the answer without visiting the step. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - condition_type: str = None, - action_start_time: str = None, - prompted: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. @@ -11584,17 +12747,16 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'prompted' in _dict: - args['prompted'] = _dict.get('prompted') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod @@ -11647,6 +12809,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11657,23 +12820,25 @@ class MessageOutputDebugTurnEventTurnEventStepVisited( """ MessageOutputDebugTurnEventTurnEventStepVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str condition_type: (optional) The type of condition (if any) that is + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str action_start_time: (optional) The time when the action started + :param str action_start_time: (optional) The time when the action started processing the message. - :attr bool has_question: (optional) Whether the step collects a customer + :param bool has_question: (optional) Whether the step collects a customer response. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - condition_type: str = None, - action_start_time: str = None, - has_question: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. @@ -11699,17 +12864,16 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'has_question' in _dict: - args['has_question'] = _dict.get('has_question') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod @@ -11762,6 +12926,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11771,30 +12936,33 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -11829,31 +12997,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11913,26 +13080,28 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( """ RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. @@ -11962,29 +13131,27 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12044,38 +13211,40 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( """ RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human + :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr str topic: (optional) A label identifying the topic of the conversation, + :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -12116,30 +13285,30 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'channels' in _dict: + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12212,11 +13381,14 @@ class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeDate. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - def __init__(self, response_type: str) -> None: + def __init__( + self, + response_type: str, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object. @@ -12233,8 +13405,8 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDate': """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDate JSON' @@ -12278,28 +13450,31 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str description: (optional) The description to show with the the + response. + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -12332,28 +13507,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12412,27 +13586,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str source: The `https:` URL of the image. + :param str title: (optional) The title to show before the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -12464,29 +13641,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -12542,27 +13718,30 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -12595,35 +13774,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12687,6 +13864,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -12695,23 +13873,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -12738,24 +13918,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12808,27 +13987,29 @@ class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeSearch. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str header: The title or introductory text to show before the response. + :param str header: The title or introductory text to show before the response. This text is defined in the search skill configuration. - :attr List[SearchResult] primary_results: An array of objects that contains the + :param List[SearchResult] primary_results: An array of objects that contains the search results to be displayed in the initial response to the user. - :attr List[SearchResult] additional_results: An array of objects that contains + :param List[SearchResult] additional_results: An array of objects that contains additional search results that can be displayed to the user upon request. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - header: str, - primary_results: List['SearchResult'], - additional_results: List['SearchResult'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + header: str, + primary_results: List['SearchResult'], + additional_results: List['SearchResult'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object. @@ -12861,39 +14042,37 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeSearch': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'header' in _dict: - args['header'] = _dict.get('header') + if (header := _dict.get('header')) is not None: + args['header'] = header else: raise ValueError( 'Required property \'header\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'primary_results' in _dict: + if (primary_results := _dict.get('primary_results')) is not None: args['primary_results'] = [ - SearchResult.from_dict(v) for v in _dict.get('primary_results') + SearchResult.from_dict(v) for v in primary_results ] else: raise ValueError( 'Required property \'primary_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'additional_results' in _dict: + if (additional_results := _dict.get('additional_results')) is not None: args['additional_results'] = [ - SearchResult.from_dict(v) - for v in _dict.get('additional_results') + SearchResult.from_dict(v) for v in additional_results ] else: raise ValueError( 'Required property \'additional_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12966,23 +14145,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -13010,30 +14191,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13094,20 +14274,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -13131,22 +14313,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13198,21 +14379,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -13237,22 +14420,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13305,30 +14487,33 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -13363,31 +14548,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 28c72313..a604775e 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -30,7 +30,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -83,12 +83,14 @@ def __init__( # Environments ######################### - def create_environment(self, - name: str, - *, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: + def create_environment( + self, + name: str, + *, + description: Optional[str] = None, + size: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create an environment. @@ -110,9 +112,11 @@ def create_environment(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_environment', + ) headers.update(sdk_headers) params = { @@ -134,19 +138,23 @@ def create_environment(self, headers['Accept'] = 'application/json' url = '/v1/environments' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_environments(self, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_environments( + self, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List environments. @@ -159,9 +167,11 @@ def list_environments(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_environments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_environments', + ) headers.update(sdk_headers) params = { @@ -175,16 +185,21 @@ def list_environments(self, headers['Accept'] = 'application/json' url = '/v1/environments' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: + def get_environment( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ Get environment info. @@ -197,9 +212,11 @@ def get_environment(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_environment', + ) headers.update(sdk_headers) params = { @@ -215,21 +232,25 @@ def get_environment(self, environment_id: str, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_environment(self, - environment_id: str, - *, - name: str = None, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: + def update_environment( + self, + environment_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + size: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update an environment. @@ -249,9 +270,11 @@ def update_environment(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_environment', + ) headers.update(sdk_headers) params = { @@ -276,17 +299,22 @@ def update_environment(self, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: + def delete_environment( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete environment. @@ -299,9 +327,11 @@ def delete_environment(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_environment', + ) headers.update(sdk_headers) params = { @@ -317,16 +347,22 @@ def delete_environment(self, environment_id: str, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_fields(self, environment_id: str, collection_ids: List[str], - **kwargs) -> DetailedResponse: + def list_fields( + self, + environment_id: str, + collection_ids: List[str], + **kwargs, + ) -> DetailedResponse: """ List fields across collections. @@ -346,9 +382,11 @@ def list_fields(self, environment_id: str, collection_ids: List[str], if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_fields', + ) headers.update(sdk_headers) params = { @@ -366,10 +404,12 @@ def list_fields(self, environment_id: str, collection_ids: List[str], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/fields'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -379,16 +419,17 @@ def list_fields(self, environment_id: str, collection_ids: List[str], ######################### def create_configuration( - self, - environment_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + name: str, + *, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + **kwargs, + ) -> DetailedResponse: """ Add configuration. @@ -434,9 +475,11 @@ def create_configuration( if source is not None: source = convert_model(source) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_configuration', + ) headers.update(sdk_headers) params = { @@ -465,20 +508,24 @@ def create_configuration( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_configurations(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_configurations( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List configurations. @@ -494,9 +541,11 @@ def list_configurations(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_configurations') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_configurations', + ) headers.update(sdk_headers) params = { @@ -514,16 +563,22 @@ def list_configurations(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: + def get_configuration( + self, + environment_id: str, + configuration_id: str, + **kwargs, + ) -> DetailedResponse: """ Get configuration details. @@ -539,9 +594,11 @@ def get_configuration(self, environment_id: str, configuration_id: str, if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_configuration', + ) headers.update(sdk_headers) params = { @@ -559,26 +616,29 @@ def get_configuration(self, environment_id: str, configuration_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def update_configuration( - self, - environment_id: str, - configuration_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + configuration_id: str, + name: str, + *, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + **kwargs, + ) -> DetailedResponse: """ Update a configuration. @@ -626,9 +686,11 @@ def update_configuration( if source is not None: source = convert_model(source) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_configuration', + ) headers.update(sdk_headers) params = { @@ -658,17 +720,23 @@ def update_configuration( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: + def delete_configuration( + self, + environment_id: str, + configuration_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a configuration. @@ -691,9 +759,11 @@ def delete_configuration(self, environment_id: str, configuration_id: str, if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_configuration', + ) headers.update(sdk_headers) params = { @@ -711,10 +781,12 @@ def delete_configuration(self, environment_id: str, configuration_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -723,14 +795,16 @@ def delete_configuration(self, environment_id: str, configuration_id: str, # Collections ######################### - def create_collection(self, - environment_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - language: str = None, - **kwargs) -> DetailedResponse: + def create_collection( + self, + environment_id: str, + name: str, + *, + description: Optional[str] = None, + configuration_id: Optional[str] = None, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a collection. @@ -751,9 +825,11 @@ def create_collection(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_collection', + ) headers.update(sdk_headers) params = { @@ -780,20 +856,24 @@ def create_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_collections(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_collections( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List collections. @@ -809,9 +889,11 @@ def list_collections(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collections') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collections', + ) headers.update(sdk_headers) params = { @@ -829,16 +911,22 @@ def list_collections(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_collection( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get collection details. @@ -854,9 +942,11 @@ def get_collection(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_collection', + ) headers.update(sdk_headers) params = { @@ -873,22 +963,26 @@ def get_collection(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_collection(self, - environment_id: str, - collection_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - **kwargs) -> DetailedResponse: + def update_collection( + self, + environment_id: str, + collection_id: str, + name: str, + *, + description: Optional[str] = None, + configuration_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a collection. @@ -910,9 +1004,11 @@ def update_collection(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_collection', + ) headers.update(sdk_headers) params = { @@ -938,17 +1034,23 @@ def update_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_collection( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a collection. @@ -964,9 +1066,11 @@ def delete_collection(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_collection', + ) headers.update(sdk_headers) params = { @@ -983,16 +1087,22 @@ def delete_collection(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_collection_fields(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_collection_fields( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ List collection fields. @@ -1010,9 +1120,11 @@ def list_collection_fields(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collection_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collection_fields', + ) headers.update(sdk_headers) params = { @@ -1029,10 +1141,12 @@ def list_collection_fields(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1041,8 +1155,12 @@ def list_collection_fields(self, environment_id: str, collection_id: str, # Query modifications ######################### - def list_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_expansions( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get the expansion list. @@ -1061,9 +1179,11 @@ def list_expansions(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_expansions', + ) headers.update(sdk_headers) params = { @@ -1080,17 +1200,23 @@ def list_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_expansions(self, environment_id: str, collection_id: str, - expansions: List['Expansion'], - **kwargs) -> DetailedResponse: + def create_expansions( + self, + environment_id: str, + collection_id: str, + expansions: List['Expansion'], + **kwargs, + ) -> DetailedResponse: """ Create or update expansion list. @@ -1126,9 +1252,11 @@ def create_expansions(self, environment_id: str, collection_id: str, raise ValueError('expansions must be provided') expansions = [convert_model(x) for x in expansions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_expansions', + ) headers.update(sdk_headers) params = { @@ -1152,17 +1280,23 @@ def create_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete the expansion list. @@ -1181,9 +1315,11 @@ def delete_expansions(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_expansions', + ) headers.update(sdk_headers) params = { @@ -1199,17 +1335,22 @@ def delete_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_tokenization_dictionary_status(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: + def get_tokenization_dictionary_status( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get tokenization dictionary status. @@ -1231,7 +1372,8 @@ def get_tokenization_dictionary_status(self, environment_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_tokenization_dictionary_status') + operation_id='get_tokenization_dictionary_status', + ) headers.update(sdk_headers) params = { @@ -1248,21 +1390,24 @@ def get_tokenization_dictionary_status(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - *, - tokenization_rules: List['TokenDictRule'] = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + collection_id: str, + *, + tokenization_rules: Optional[List['TokenDictRule']] = None, + **kwargs, + ) -> DetailedResponse: """ Create tokenization dictionary. @@ -1289,7 +1434,8 @@ def create_tokenization_dictionary( sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_tokenization_dictionary') + operation_id='create_tokenization_dictionary', + ) headers.update(sdk_headers) params = { @@ -1313,18 +1459,23 @@ def create_tokenization_dictionary( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_tokenization_dictionary(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: + def delete_tokenization_dictionary( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete tokenization dictionary. @@ -1345,7 +1496,8 @@ def delete_tokenization_dictionary(self, environment_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_tokenization_dictionary') + operation_id='delete_tokenization_dictionary', + ) headers.update(sdk_headers) params = { @@ -1361,16 +1513,22 @@ def delete_tokenization_dictionary(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_stopword_list_status(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_stopword_list_status( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get stopword list status. @@ -1388,9 +1546,11 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_stopword_list_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_stopword_list_status', + ) headers.update(sdk_headers) params = { @@ -1407,21 +1567,25 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_stopword_list(self, - environment_id: str, - collection_id: str, - stopword_file: BinaryIO, - *, - stopword_filename: str = None, - **kwargs) -> DetailedResponse: + def create_stopword_list( + self, + environment_id: str, + collection_id: str, + stopword_file: BinaryIO, + *, + stopword_filename: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create stopword list. @@ -1443,9 +1607,11 @@ def create_stopword_list(self, if stopword_file is None: raise ValueError('stopword_file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1470,17 +1636,23 @@ def create_stopword_list(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_stopword_list(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_stopword_list( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom stopword list. @@ -1499,9 +1671,11 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1517,10 +1691,12 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1529,15 +1705,17 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, # Documents ######################### - def add_document(self, - environment_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def add_document( + self, + environment_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a document. @@ -1585,9 +1763,11 @@ def add_document(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_document', + ) headers.update(sdk_headers) params = { @@ -1615,17 +1795,24 @@ def add_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_status(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def get_document_status( + self, + environment_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document details. @@ -1649,9 +1836,11 @@ def get_document_status(self, environment_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_document_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_document_status', + ) headers.update(sdk_headers) params = { @@ -1669,24 +1858,28 @@ def get_document_status(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document(self, - environment_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def update_document( + self, + environment_id: str, + collection_id: str, + document_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document. @@ -1721,9 +1914,11 @@ def update_document(self, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_document', + ) headers.update(sdk_headers) params = { @@ -1752,17 +1947,24 @@ def update_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def delete_document( + self, + environment_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document. @@ -1785,9 +1987,11 @@ def delete_document(self, environment_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -1805,10 +2009,12 @@ def delete_document(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1817,32 +2023,34 @@ def delete_document(self, environment_id: str, collection_id: str, # Queries ######################### - def query(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - spelling_suggestions: bool = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: + def query( + self, + environment_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[str] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[str] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[str] = None, + similar_fields: Optional[str] = None, + bias: Optional[str] = None, + spelling_suggestions: Optional[bool] = None, + x_watson_logging_opt_out: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Query a collection. @@ -1938,9 +2146,11 @@ def query(self, headers = { 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query', + ) headers.update(sdk_headers) params = { @@ -1983,37 +2193,41 @@ def query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def query_notices(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - passages_fields: List[str] = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: + def query_notices( + self, + environment_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[List[str]] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[List[str]] = None, + similar_fields: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Query system notices. @@ -2089,9 +2303,11 @@ def query_notices(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_notices', + ) headers.update(sdk_headers) params = { @@ -2125,39 +2341,43 @@ def query_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def federated_query(self, - environment_id: str, - collection_ids: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: + def federated_query( + self, + environment_id: str, + collection_ids: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[str] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[str] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[str] = None, + similar_fields: Optional[str] = None, + bias: Optional[str] = None, + x_watson_logging_opt_out: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Query multiple collections. @@ -2248,9 +2468,11 @@ def federated_query(self, headers = { 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query', + ) headers.update(sdk_headers) params = { @@ -2293,33 +2515,37 @@ def federated_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/query'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def federated_query_notices(self, - environment_id: str, - collection_ids: List[str], - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: + def federated_query_notices( + self, + environment_id: str, + collection_ids: List[str], + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + highlight: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[List[str]] = None, + similar_fields: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Query multiple collection system notices. @@ -2386,9 +2612,11 @@ def federated_query_notices(self, if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query_notices', + ) headers.update(sdk_headers) params = { @@ -2419,22 +2647,26 @@ def federated_query_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - environment_id: str, - collection_id: str, - prefix: str, - *, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + def get_autocompletion( + self, + environment_id: str, + collection_id: str, + prefix: str, + *, + field: Optional[str] = None, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Get Autocomplete Suggestions. @@ -2462,9 +2694,11 @@ def get_autocompletion(self, if not prefix: raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_autocompletion') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_autocompletion', + ) headers.update(sdk_headers) params = { @@ -2484,10 +2718,12 @@ def get_autocompletion(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2496,8 +2732,12 @@ def get_autocompletion(self, # Training data ######################### - def list_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_training_data( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ List training data. @@ -2515,9 +2755,11 @@ def list_training_data(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_data', + ) headers.update(sdk_headers) params = { @@ -2534,22 +2776,26 @@ def list_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_training_data(self, - environment_id: str, - collection_id: str, - *, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None, - **kwargs) -> DetailedResponse: + def add_training_data( + self, + environment_id: str, + collection_id: str, + *, + natural_language_query: Optional[str] = None, + filter: Optional[str] = None, + examples: Optional[List['TrainingExample']] = None, + **kwargs, + ) -> DetailedResponse: """ Add query to training data. @@ -2576,9 +2822,11 @@ def add_training_data(self, if examples is not None: examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_training_data', + ) headers.update(sdk_headers) params = { @@ -2604,17 +2852,23 @@ def add_training_data(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_all_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_all_training_data( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete all training data. @@ -2632,9 +2886,11 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_all_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_all_training_data', + ) headers.update(sdk_headers) params = { @@ -2650,16 +2906,23 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def get_training_data( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Get details about a query. @@ -2681,9 +2944,11 @@ def get_training_data(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_data', + ) headers.update(sdk_headers) params = { @@ -2701,16 +2966,23 @@ def get_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def delete_training_data( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a training data query. @@ -2732,9 +3004,11 @@ def delete_training_data(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_data', + ) headers.update(sdk_headers) params = { @@ -2751,16 +3025,23 @@ def delete_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_training_examples(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def list_training_examples( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ List examples for a training data query. @@ -2781,9 +3062,11 @@ def list_training_examples(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_examples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_examples', + ) headers.update(sdk_headers) params = { @@ -2801,23 +3084,27 @@ def list_training_examples(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: + def create_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + *, + document_id: Optional[str] = None, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Add example to training data query. @@ -2843,9 +3130,11 @@ def create_training_example(self, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_training_example', + ) headers.update(sdk_headers) params = { @@ -2872,18 +3161,25 @@ def create_training_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: + def delete_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete example for training data query. @@ -2907,9 +3203,11 @@ def delete_training_example(self, environment_id: str, collection_id: str, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_example', + ) headers.update(sdk_headers) params = { @@ -2928,23 +3226,27 @@ def delete_training_example(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - *, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: + def update_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + *, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Change label or cross reference for example. @@ -2970,9 +3272,11 @@ def update_training_example(self, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_training_example', + ) headers.update(sdk_headers) params = { @@ -3000,18 +3304,25 @@ def update_training_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: + def get_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + **kwargs, + ) -> DetailedResponse: """ Get details for training data example. @@ -3035,9 +3346,11 @@ def get_training_example(self, environment_id: str, collection_id: str, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_example', + ) headers.update(sdk_headers) params = { @@ -3057,10 +3370,12 @@ def get_training_example(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3069,7 +3384,11 @@ def get_training_example(self, environment_id: str, collection_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3090,9 +3409,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3105,10 +3426,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3117,8 +3440,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: # Events and feedback ######################### - def create_event(self, type: str, data: 'EventData', - **kwargs) -> DetailedResponse: + def create_event( + self, + type: str, + data: 'EventData', + **kwargs, + ) -> DetailedResponse: """ Create event. @@ -3139,9 +3466,11 @@ def create_event(self, type: str, data: 'EventData', raise ValueError('data must be provided') data = convert_model(data) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_event', + ) headers.update(sdk_headers) params = { @@ -3162,23 +3491,27 @@ def create_event(self, type: str, data: 'EventData', headers['Accept'] = 'application/json' url = '/v1/events' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def query_log(self, - *, - filter: str = None, - query: str = None, - count: int = None, - offset: int = None, - sort: List[str] = None, - **kwargs) -> DetailedResponse: + def query_log( + self, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Search the query and event log. @@ -3208,9 +3541,11 @@ def query_log(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_log') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_log', + ) headers.update(sdk_headers) params = { @@ -3228,20 +3563,24 @@ def query_log(self, headers['Accept'] = 'application/json' url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries over time. @@ -3260,9 +3599,11 @@ def get_metrics_query(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query', + ) headers.update(sdk_headers) params = { @@ -3278,20 +3619,24 @@ def get_metrics_query(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_event(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_event( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries with an event over time. @@ -3311,9 +3656,11 @@ def get_metrics_query_event(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_event', + ) headers.update(sdk_headers) params = { @@ -3329,20 +3676,24 @@ def get_metrics_query_event(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_no_results(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_no_results( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries with no search results over time. @@ -3364,7 +3715,8 @@ def get_metrics_query_no_results(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_metrics_query_no_results') + operation_id='get_metrics_query_no_results', + ) headers.update(sdk_headers) params = { @@ -3380,20 +3732,24 @@ def get_metrics_query_no_results(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_event_rate(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_event_rate( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Percentage of queries with an associated event. @@ -3413,9 +3769,11 @@ def get_metrics_event_rate(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_event_rate') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_event_rate', + ) headers.update(sdk_headers) params = { @@ -3431,18 +3789,22 @@ def get_metrics_event_rate(self, headers['Accept'] = 'application/json' url = '/v1/metrics/event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_token_event(self, - *, - count: int = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_token_event( + self, + *, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Most frequent query tokens with an event. @@ -3462,7 +3824,8 @@ def get_metrics_query_token_event(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_metrics_query_token_event') + operation_id='get_metrics_query_token_event', + ) headers.update(sdk_headers) params = { @@ -3476,10 +3839,12 @@ def get_metrics_query_token_event(self, headers['Accept'] = 'application/json' url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3488,8 +3853,11 @@ def get_metrics_query_token_event(self, # Credentials ######################### - def list_credentials(self, environment_id: str, - **kwargs) -> DetailedResponse: + def list_credentials( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ List credentials. @@ -3506,9 +3874,11 @@ def list_credentials(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_credentials', + ) headers.update(sdk_headers) params = { @@ -3525,21 +3895,25 @@ def list_credentials(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_credentials(self, - environment_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: + def create_credentials( + self, + environment_id: str, + *, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + **kwargs, + ) -> DetailedResponse: """ Create credentials. @@ -3577,9 +3951,11 @@ def create_credentials(self, if status is not None: status = convert_model(status) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_credentials', + ) headers.update(sdk_headers) params = { @@ -3605,17 +3981,23 @@ def create_credentials(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: + def get_credentials( + self, + environment_id: str, + credential_id: str, + **kwargs, + ) -> DetailedResponse: """ View Credentials. @@ -3636,9 +4018,11 @@ def get_credentials(self, environment_id: str, credential_id: str, if not credential_id: raise ValueError('credential_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_credentials', + ) headers.update(sdk_headers) params = { @@ -3655,22 +4039,26 @@ def get_credentials(self, environment_id: str, credential_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_credentials(self, - environment_id: str, - credential_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: + def update_credentials( + self, + environment_id: str, + credential_id: str, + *, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + **kwargs, + ) -> DetailedResponse: """ Update credentials. @@ -3711,9 +4099,11 @@ def update_credentials(self, if status is not None: status = convert_model(status) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_credentials', + ) headers.update(sdk_headers) params = { @@ -3739,17 +4129,23 @@ def update_credentials(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: + def delete_credentials( + self, + environment_id: str, + credential_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete credentials. @@ -3768,9 +4164,11 @@ def delete_credentials(self, environment_id: str, credential_id: str, if not credential_id: raise ValueError('credential_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_credentials', + ) headers.update(sdk_headers) params = { @@ -3787,10 +4185,12 @@ def delete_credentials(self, environment_id: str, credential_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3799,7 +4199,11 @@ def delete_credentials(self, environment_id: str, credential_id: str, # gatewayConfiguration ######################### - def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: + def list_gateways( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ List Gateways. @@ -3814,9 +4218,11 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_gateways') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_gateways', + ) headers.update(sdk_headers) params = { @@ -3833,19 +4239,23 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_gateway(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def create_gateway( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create Gateway. @@ -3861,9 +4271,11 @@ def create_gateway(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_gateway', + ) headers.update(sdk_headers) params = { @@ -3887,17 +4299,23 @@ def create_gateway(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: + def get_gateway( + self, + environment_id: str, + gateway_id: str, + **kwargs, + ) -> DetailedResponse: """ List Gateway Details. @@ -3915,9 +4333,11 @@ def get_gateway(self, environment_id: str, gateway_id: str, if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_gateway', + ) headers.update(sdk_headers) params = { @@ -3934,16 +4354,22 @@ def get_gateway(self, environment_id: str, gateway_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: + def delete_gateway( + self, + environment_id: str, + gateway_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete Gateway. @@ -3961,9 +4387,11 @@ def delete_gateway(self, environment_id: str, gateway_id: str, if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_gateway', + ) headers.update(sdk_headers) params = { @@ -3980,10 +4408,12 @@ def delete_gateway(self, environment_id: str, gateway_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3998,6 +4428,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -4015,6 +4446,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -4032,6 +4464,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4044,6 +4477,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4056,6 +4490,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4068,6 +4503,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4076,49 +4512,51 @@ class ResultType(str, Enum): ############################################################################## -class Collection(): +class Collection: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. - :attr str description: (optional) The description of the collection. - :attr datetime created: (optional) The creation date of the collection in the + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: (optional) The name of the collection. + :param str description: (optional) The description of the collection. + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the collection was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str status: (optional) The status of the collection. - :attr str configuration_id: (optional) The unique identifier of the collection's - configuration. - :attr str language: (optional) The language of the documents stored in the + :param datetime updated: (optional) The timestamp of when the collection was + last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str status: (optional) The status of the collection. + :param str configuration_id: (optional) The unique identifier of the + collection's configuration. + :param str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). - :attr DocumentCounts document_counts: (optional) Object containing collection + :param DocumentCounts document_counts: (optional) Object containing collection document count information. - :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage + :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. - :attr TrainingStatus training_status: (optional) Training status details. - :attr CollectionCrawlStatus crawl_status: (optional) Object containing + :param TrainingStatus training_status: (optional) Training status details. + :param CollectionCrawlStatus crawl_status: (optional) Object containing information about the crawl status of this collection. - :attr SduStatus smart_document_understanding: (optional) Object containing smart - document understanding information for this collection. - """ - - def __init__(self, - *, - collection_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - configuration_id: str = None, - language: str = None, - document_counts: 'DocumentCounts' = None, - disk_usage: 'CollectionDiskUsage' = None, - training_status: 'TrainingStatus' = None, - crawl_status: 'CollectionCrawlStatus' = None, - smart_document_understanding: 'SduStatus' = None) -> None: + :param SduStatus smart_document_understanding: (optional) Object containing + smart document understanding information for this collection. + """ + + def __init__( + self, + *, + collection_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + configuration_id: Optional[str] = None, + language: Optional[str] = None, + document_counts: Optional['DocumentCounts'] = None, + disk_usage: Optional['CollectionDiskUsage'] = None, + training_status: Optional['TrainingStatus'] = None, + crawl_status: Optional['CollectionCrawlStatus'] = None, + smart_document_understanding: Optional['SduStatus'] = None, + ) -> None: """ Initialize a Collection object. @@ -4157,37 +4595,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'document_counts' in _dict: - args['document_counts'] = DocumentCounts.from_dict( - _dict.get('document_counts')) - if 'disk_usage' in _dict: - args['disk_usage'] = CollectionDiskUsage.from_dict( - _dict.get('disk_usage')) - if 'training_status' in _dict: - args['training_status'] = TrainingStatus.from_dict( - _dict.get('training_status')) - if 'crawl_status' in _dict: - args['crawl_status'] = CollectionCrawlStatus.from_dict( - _dict.get('crawl_status')) - if 'smart_document_understanding' in _dict: + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (language := _dict.get('language')) is not None: + args['language'] = language + if (document_counts := _dict.get('document_counts')) is not None: + args['document_counts'] = DocumentCounts.from_dict(document_counts) + if (disk_usage := _dict.get('disk_usage')) is not None: + args['disk_usage'] = CollectionDiskUsage.from_dict(disk_usage) + if (training_status := _dict.get('training_status')) is not None: + args['training_status'] = TrainingStatus.from_dict(training_status) + if (crawl_status := _dict.get('crawl_status')) is not None: + args['crawl_status'] = CollectionCrawlStatus.from_dict(crawl_status) + if (smart_document_understanding := + _dict.get('smart_document_understanding')) is not None: args['smart_document_understanding'] = SduStatus.from_dict( - _dict.get('smart_document_understanding')) + smart_document_understanding) return cls(**args) @classmethod @@ -4271,20 +4706,25 @@ class StatusEnum(str, Enum): """ The status of the collection. """ + ACTIVE = 'active' PENDING = 'pending' MAINTENANCE = 'maintenance' -class CollectionCrawlStatus(): +class CollectionCrawlStatus: """ Object containing information about the crawl status of this collection. - :attr SourceStatus source_crawl: (optional) Object containing source crawl + :param SourceStatus source_crawl: (optional) Object containing source crawl status information. """ - def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: + def __init__( + self, + *, + source_crawl: Optional['SourceStatus'] = None, + ) -> None: """ Initialize a CollectionCrawlStatus object. @@ -4297,9 +4737,8 @@ def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} - if 'source_crawl' in _dict: - args['source_crawl'] = SourceStatus.from_dict( - _dict.get('source_crawl')) + if (source_crawl := _dict.get('source_crawl')) is not None: + args['source_crawl'] = SourceStatus.from_dict(source_crawl) return cls(**args) @classmethod @@ -4336,14 +4775,18 @@ def __ne__(self, other: 'CollectionCrawlStatus') -> bool: return not self == other -class CollectionDiskUsage(): +class CollectionDiskUsage: """ Summary of the disk usage statistics for this collection. - :attr int used_bytes: (optional) Number of bytes used by the collection. + :param int used_bytes: (optional) Number of bytes used by the collection. """ - def __init__(self, *, used_bytes: int = None) -> None: + def __init__( + self, + *, + used_bytes: Optional[int] = None, + ) -> None: """ Initialize a CollectionDiskUsage object. @@ -4354,8 +4797,8 @@ def __init__(self, *, used_bytes: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') + if (used_bytes := _dict.get('used_bytes')) is not None: + args['used_bytes'] = used_bytes return cls(**args) @classmethod @@ -4390,19 +4833,22 @@ def __ne__(self, other: 'CollectionDiskUsage') -> bool: return not self == other -class CollectionUsage(): +class CollectionUsage: """ Summary of the collection usage in the environment. - :attr int available: (optional) Number of active collections in the environment. - :attr int maximum_allowed: (optional) Total number of collections allowed in the + :param int available: (optional) Number of active collections in the environment. + :param int maximum_allowed: (optional) Total number of collections allowed in + the environment. """ - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a CollectionUsage object. @@ -4414,10 +4860,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionUsage': """Initialize a CollectionUsage object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -4455,15 +4901,19 @@ def __ne__(self, other: 'CollectionUsage') -> bool: return not self == other -class Completions(): +class Completions: """ An object containing an array of autocompletion suggestions. - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. + :param List[str] completions: (optional) Array of autcomplete suggestion based + on the provided prefix. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__( + self, + *, + completions: Optional[List[str]] = None, + ) -> None: """ Initialize a Completions object. @@ -4476,8 +4926,8 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if (completions := _dict.get('completions')) is not None: + args['completions'] = completions return cls(**args) @classmethod @@ -4511,40 +4961,42 @@ def __ne__(self, other: 'Completions') -> bool: return not self == other -class Configuration(): +class Configuration: """ A custom configuration for the environment. - :attr str configuration_id: (optional) The unique identifier of the + :param str configuration_id: (optional) The unique identifier of the configuration. - :attr str name: The name of the configuration. - :attr datetime created: (optional) The creation date of the configuration in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the configuration was + :param str name: The name of the configuration. + :param datetime created: (optional) The creation date of the configuration in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param datetime updated: (optional) The timestamp of when the configuration was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str description: (optional) The description of the configuration, if + :param str description: (optional) The description of the configuration, if available. - :attr Conversions conversions: (optional) Document conversion settings. - :attr List[Enrichment] enrichments: (optional) An array of document enrichment + :param Conversions conversions: (optional) Document conversion settings. + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :attr List[NormalizationOperation] normalizations: (optional) Defines operations - that can be used to transform the final output JSON into a normalized form. - Operations are executed in the order that they appear in the array. - :attr Source source: (optional) Object containing source parameters for the + :param List[NormalizationOperation] normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a normalized + form. Operations are executed in the order that they appear in the array. + :param Source source: (optional) Object containing source parameters for the configuration. """ - def __init__(self, - name: str, - *, - configuration_id: str = None, - created: datetime = None, - updated: datetime = None, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None) -> None: + def __init__( + self, + name: str, + *, + configuration_id: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + ) -> None: """ Initialize a Configuration object. @@ -4575,33 +5027,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Configuration': """Initialize a Configuration object from a json dictionary.""" args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Configuration JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conversions' in _dict: - args['conversions'] = Conversions.from_dict( - _dict.get('conversions')) - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(v) for v in _dict.get('enrichments') - ] - if 'normalizations' in _dict: + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (conversions := _dict.get('conversions')) is not None: + args['conversions'] = Conversions.from_dict(conversions) + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] + if (normalizations := _dict.get('normalizations')) is not None: args['normalizations'] = [ - NormalizationOperation.from_dict(v) - for v in _dict.get('normalizations') + NormalizationOperation.from_dict(v) for v in normalizations ] - if 'source' in _dict: - args['source'] = Source.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = Source.from_dict(source) return cls(**args) @classmethod @@ -4670,19 +5118,19 @@ def __ne__(self, other: 'Configuration') -> bool: return not self == other -class Conversions(): +class Conversions: """ Document conversion settings. - :attr PdfSettings pdf: (optional) A list of PDF conversion settings. - :attr WordSettings word: (optional) A list of Word conversion settings. - :attr HtmlSettings html: (optional) A list of HTML conversion settings. - :attr SegmentSettings segment: (optional) A list of Document Segmentation + :param PdfSettings pdf: (optional) A list of PDF conversion settings. + :param WordSettings word: (optional) A list of Word conversion settings. + :param HtmlSettings html: (optional) A list of HTML conversion settings. + :param SegmentSettings segment: (optional) A list of Document Segmentation settings. - :attr List[NormalizationOperation] json_normalizations: (optional) Defines + :param List[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. - :attr bool image_text_recognition: (optional) When `true`, automatic text + :param bool image_text_recognition: (optional) When `true`, automatic text extraction from images (this includes images embedded in supported document formats, for example PDF, and suppported image formats, for example TIFF) is performed on documents uploaded to the collection. This field is supported on @@ -4690,14 +5138,16 @@ class Conversions(): recognition. """ - def __init__(self, - *, - pdf: 'PdfSettings' = None, - word: 'WordSettings' = None, - html: 'HtmlSettings' = None, - segment: 'SegmentSettings' = None, - json_normalizations: List['NormalizationOperation'] = None, - image_text_recognition: bool = None) -> None: + def __init__( + self, + *, + pdf: Optional['PdfSettings'] = None, + word: Optional['WordSettings'] = None, + html: Optional['HtmlSettings'] = None, + segment: Optional['SegmentSettings'] = None, + json_normalizations: Optional[List['NormalizationOperation']] = None, + image_text_recognition: Optional[bool] = None, + ) -> None: """ Initialize a Conversions object. @@ -4728,21 +5178,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Conversions': """Initialize a Conversions object from a json dictionary.""" args = {} - if 'pdf' in _dict: - args['pdf'] = PdfSettings.from_dict(_dict.get('pdf')) - if 'word' in _dict: - args['word'] = WordSettings.from_dict(_dict.get('word')) - if 'html' in _dict: - args['html'] = HtmlSettings.from_dict(_dict.get('html')) - if 'segment' in _dict: - args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) - if 'json_normalizations' in _dict: + if (pdf := _dict.get('pdf')) is not None: + args['pdf'] = PdfSettings.from_dict(pdf) + if (word := _dict.get('word')) is not None: + args['word'] = WordSettings.from_dict(word) + if (html := _dict.get('html')) is not None: + args['html'] = HtmlSettings.from_dict(html) + if (segment := _dict.get('segment')) is not None: + args['segment'] = SegmentSettings.from_dict(segment) + if (json_normalizations := + _dict.get('json_normalizations')) is not None: args['json_normalizations'] = [ - NormalizationOperation.from_dict(v) - for v in _dict.get('json_normalizations') + NormalizationOperation.from_dict(v) for v in json_normalizations ] - if 'image_text_recognition' in _dict: - args['image_text_recognition'] = _dict.get('image_text_recognition') + if (image_text_recognition := + _dict.get('image_text_recognition')) is not None: + args['image_text_recognition'] = image_text_recognition return cls(**args) @classmethod @@ -4807,15 +5258,20 @@ def __ne__(self, other: 'Conversions') -> bool: return not self == other -class CreateEventResponse(): +class CreateEventResponse: """ An object defining the event being created. - :attr str type: (optional) The event type that was created. - :attr EventData data: (optional) Query event data object. + :param str type: (optional) The event type that was created. + :param EventData data: (optional) Query event data object. """ - def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + data: Optional['EventData'] = None, + ) -> None: """ Initialize a CreateEventResponse object. @@ -4829,10 +5285,10 @@ def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': """Initialize a CreateEventResponse object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'data' in _dict: - args['data'] = EventData.from_dict(_dict.get('data')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (data := _dict.get('data')) is not None: + args['data'] = EventData.from_dict(data) return cls(**args) @classmethod @@ -4874,15 +5330,16 @@ class TypeEnum(str, Enum): """ The event type that was created. """ + CLICK = 'click' -class CredentialDetails(): +class CredentialDetails: """ Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr str credential_type: (optional) The authentication method for this + :param str credential_type: (optional) The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` @@ -4892,95 +5349,98 @@ class CredentialDetails(): - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - :attr str client_id: (optional) The **client_id** of the source that these + :param str client_id: (optional) The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. - :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that + :param str enterprise_id: (optional) The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. - :attr str url: (optional) The **url** of the source that these credentials + :param str url: (optional) The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. - :attr str username: (optional) The **username** of the source that these + :param str username: (optional) The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - :attr str organization_url: (optional) The **organization_url** of the source + :param str organization_url: (optional) The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. - :attr str site_collection_path: (optional) The **site_collection.path** of the + :param str site_collection_path: (optional) The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :attr str client_secret: (optional) The **client_secret** of the source that + :param str client_secret: (optional) The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str public_key_id: (optional) The **public_key_id** of the source that + :param str public_key_id: (optional) The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str private_key: (optional) The **private_key** of the source that these + :param str private_key: (optional) The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str passphrase: (optional) The **passphrase** of the source that these + :param str passphrase: (optional) The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str password: (optional) The **password** of the source that these + :param str password: (optional) The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntlm_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. - :attr str gateway_id: (optional) The ID of the **gateway** to be connected + :param str gateway_id: (optional) The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. - :attr str source_version: (optional) The type of Sharepoint repository to + :param str source_version: (optional) The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. + :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. If a port is not supplied, the default to port `80` for http and port `443` for https connections are used. - :attr str domain: (optional) The domain used to log in to your OnPrem SharePoint - account. Only valid, and required, with a **source_version** of `2016`. - :attr str endpoint: (optional) The endpoint associated with the cloud object + :param str domain: (optional) The domain used to log in to your OnPrem + SharePoint account. Only valid, and required, with a **source_version** of + `2016`. + :param str endpoint: (optional) The endpoint associated with the cloud object store that your are connecting to. Only valid, and required, with a **credential_type** of `aws4_hmac`. - :attr str access_key_id: (optional) The access key ID associated with the cloud + :param str access_key_id: (optional) The access key ID associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :attr str secret_access_key: (optional) The secret access key associated with + :param str secret_access_key: (optional) The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ - def __init__(self, - *, - credential_type: str = None, - client_id: str = None, - enterprise_id: str = None, - url: str = None, - username: str = None, - organization_url: str = None, - site_collection_path: str = None, - client_secret: str = None, - public_key_id: str = None, - private_key: str = None, - passphrase: str = None, - password: str = None, - gateway_id: str = None, - source_version: str = None, - web_application_url: str = None, - domain: str = None, - endpoint: str = None, - access_key_id: str = None, - secret_access_key: str = None) -> None: + def __init__( + self, + *, + credential_type: Optional[str] = None, + client_id: Optional[str] = None, + enterprise_id: Optional[str] = None, + url: Optional[str] = None, + username: Optional[str] = None, + organization_url: Optional[str] = None, + site_collection_path: Optional[str] = None, + client_secret: Optional[str] = None, + public_key_id: Optional[str] = None, + private_key: Optional[str] = None, + passphrase: Optional[str] = None, + password: Optional[str] = None, + gateway_id: Optional[str] = None, + source_version: Optional[str] = None, + web_application_url: Optional[str] = None, + domain: Optional[str] = None, + endpoint: Optional[str] = None, + access_key_id: Optional[str] = None, + secret_access_key: Optional[str] = None, + ) -> None: """ Initialize a CredentialDetails object. @@ -5091,44 +5551,46 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CredentialDetails': """Initialize a CredentialDetails object from a json dictionary.""" args = {} - if 'credential_type' in _dict: - args['credential_type'] = _dict.get('credential_type') - if 'client_id' in _dict: - args['client_id'] = _dict.get('client_id') - if 'enterprise_id' in _dict: - args['enterprise_id'] = _dict.get('enterprise_id') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'username' in _dict: - args['username'] = _dict.get('username') - if 'organization_url' in _dict: - args['organization_url'] = _dict.get('organization_url') - if 'site_collection.path' in _dict: - args['site_collection_path'] = _dict.get('site_collection.path') - if 'client_secret' in _dict: - args['client_secret'] = _dict.get('client_secret') - if 'public_key_id' in _dict: - args['public_key_id'] = _dict.get('public_key_id') - if 'private_key' in _dict: - args['private_key'] = _dict.get('private_key') - if 'passphrase' in _dict: - args['passphrase'] = _dict.get('passphrase') - if 'password' in _dict: - args['password'] = _dict.get('password') - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'source_version' in _dict: - args['source_version'] = _dict.get('source_version') - if 'web_application_url' in _dict: - args['web_application_url'] = _dict.get('web_application_url') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'endpoint' in _dict: - args['endpoint'] = _dict.get('endpoint') - if 'access_key_id' in _dict: - args['access_key_id'] = _dict.get('access_key_id') - if 'secret_access_key' in _dict: - args['secret_access_key'] = _dict.get('secret_access_key') + if (credential_type := _dict.get('credential_type')) is not None: + args['credential_type'] = credential_type + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (enterprise_id := _dict.get('enterprise_id')) is not None: + args['enterprise_id'] = enterprise_id + if (url := _dict.get('url')) is not None: + args['url'] = url + if (username := _dict.get('username')) is not None: + args['username'] = username + if (organization_url := _dict.get('organization_url')) is not None: + args['organization_url'] = organization_url + if (site_collection_path := + _dict.get('site_collection.path')) is not None: + args['site_collection_path'] = site_collection_path + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (public_key_id := _dict.get('public_key_id')) is not None: + args['public_key_id'] = public_key_id + if (private_key := _dict.get('private_key')) is not None: + args['private_key'] = private_key + if (passphrase := _dict.get('passphrase')) is not None: + args['passphrase'] = passphrase + if (password := _dict.get('password')) is not None: + args['password'] = password + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (source_version := _dict.get('source_version')) is not None: + args['source_version'] = source_version + if (web_application_url := + _dict.get('web_application_url')) is not None: + args['web_application_url'] = web_application_url + if (domain := _dict.get('domain')) is not None: + args['domain'] = domain + if (endpoint := _dict.get('endpoint')) is not None: + args['endpoint'] = endpoint + if (access_key_id := _dict.get('access_key_id')) is not None: + args['access_key_id'] = access_key_id + if (secret_access_key := _dict.get('secret_access_key')) is not None: + args['secret_access_key'] = secret_access_key return cls(**args) @classmethod @@ -5215,6 +5677,7 @@ class CredentialTypeEnum(str, Enum): - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. """ + OAUTH2 = 'oauth2' SAML = 'saml' USERNAME_PASSWORD = 'username_password' @@ -5228,16 +5691,17 @@ class SourceVersionEnum(str, Enum): The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. """ + ONLINE = 'online' -class Credentials(): +class Credentials: """ Object containing credential information. - :attr str credential_id: (optional) Unique identifier for this set of + :param str credential_id: (optional) Unique identifier for this set of credentials. - :attr str source_type: (optional) The source that this credentials object + :param str source_type: (optional) The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. @@ -5247,19 +5711,21 @@ class Credentials(): - `web_crawl` indicates the credentials are used to perform a web crawl. = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. - :attr CredentialDetails credential_details: (optional) Object containing details - of the stored credentials. + :param CredentialDetails credential_details: (optional) Object containing + details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr StatusDetails status: (optional) Object that contains details about the + :param StatusDetails status: (optional) Object that contains details about the status of the authentication process. """ - def __init__(self, - *, - credential_id: str = None, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None) -> None: + def __init__( + self, + *, + credential_id: Optional[str] = None, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + ) -> None: """ Initialize a Credentials object. @@ -5289,15 +5755,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Credentials': """Initialize a Credentials object from a json dictionary.""" args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'source_type' in _dict: - args['source_type'] = _dict.get('source_type') - if 'credential_details' in _dict: + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (source_type := _dict.get('source_type')) is not None: + args['source_type'] = source_type + if (credential_details := _dict.get('credential_details')) is not None: args['credential_details'] = CredentialDetails.from_dict( - _dict.get('credential_details')) - if 'status' in _dict: - args['status'] = StatusDetails.from_dict(_dict.get('status')) + credential_details) + if (status := _dict.get('status')) is not None: + args['status'] = StatusDetails.from_dict(status) return cls(**args) @classmethod @@ -5357,6 +5823,7 @@ class SourceTypeEnum(str, Enum): = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. """ + BOX = 'box' SALESFORCE = 'salesforce' SHAREPOINT = 'sharepoint' @@ -5364,15 +5831,19 @@ class SourceTypeEnum(str, Enum): CLOUD_OBJECT_STORAGE = 'cloud_object_storage' -class CredentialsList(): +class CredentialsList: """ Object containing array of credential definitions. - :attr List[Credentials] credentials: (optional) An array of credential + :param List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ - def __init__(self, *, credentials: List['Credentials'] = None) -> None: + def __init__( + self, + *, + credentials: Optional[List['Credentials']] = None, + ) -> None: """ Initialize a CredentialsList object. @@ -5385,9 +5856,9 @@ def __init__(self, *, credentials: List['Credentials'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CredentialsList': """Initialize a CredentialsList object from a json dictionary.""" args = {} - if 'credentials' in _dict: + if (credentials := _dict.get('credentials')) is not None: args['credentials'] = [ - Credentials.from_dict(v) for v in _dict.get('credentials') + Credentials.from_dict(v) for v in credentials ] return cls(**args) @@ -5428,17 +5899,21 @@ def __ne__(self, other: 'CredentialsList') -> bool: return not self == other -class DeleteCollectionResponse(): +class DeleteCollectionResponse: """ Response object returned when deleting a colleciton. - :attr str collection_id: The unique identifier of the collection that is being + :param str collection_id: The unique identifier of the collection that is being deleted. - :attr str status: The status of the collection. The status of a successful + :param str status: The status of the collection. The status of a successful deletion operation is `deleted`. """ - def __init__(self, collection_id: str, status: str) -> None: + def __init__( + self, + collection_id: str, + status: str, + ) -> None: """ Initialize a DeleteCollectionResponse object. @@ -5454,14 +5929,14 @@ def __init__(self, collection_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteCollectionResponse JSON' @@ -5505,24 +5980,27 @@ class StatusEnum(str, Enum): The status of the collection. The status of a successful deletion operation is `deleted`. """ + DELETED = 'deleted' -class DeleteConfigurationResponse(): +class DeleteConfigurationResponse: """ Information returned when a configuration is deleted. - :attr str configuration_id: The unique identifier for the configuration. - :attr str status: Status of the configuration. A deleted configuration has the + :param str configuration_id: The unique identifier for the configuration. + :param str status: Status of the configuration. A deleted configuration has the status deleted. - :attr List[Notice] notices: (optional) An array of notice messages, if any. + :param List[Notice] notices: (optional) An array of notice messages, if any. """ - def __init__(self, - configuration_id: str, - status: str, - *, - notices: List['Notice'] = None) -> None: + def __init__( + self, + configuration_id: str, + status: str, + *, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DeleteConfigurationResponse object. @@ -5540,22 +6018,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id else: raise ValueError( 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteConfigurationResponse JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -5603,22 +6079,25 @@ class StatusEnum(str, Enum): """ Status of the configuration. A deleted configuration has the status deleted. """ + DELETED = 'deleted' -class DeleteCredentials(): +class DeleteCredentials: """ Object returned after credentials are deleted. - :attr str credential_id: (optional) The unique identifier of the credentials + :param str credential_id: (optional) The unique identifier of the credentials that have been deleted. - :attr str status: (optional) The status of the deletion request. + :param str status: (optional) The status of the deletion request. """ - def __init__(self, - *, - credential_id: str = None, - status: str = None) -> None: + def __init__( + self, + *, + credential_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteCredentials object. @@ -5633,10 +6112,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': """Initialize a DeleteCredentials object from a json dictionary.""" args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5675,19 +6154,25 @@ class StatusEnum(str, Enum): """ The status of the deletion request. """ + DELETED = 'deleted' -class DeleteDocumentResponse(): +class DeleteDocumentResponse: """ Information returned when a document is deleted. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document has the status deleted. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5702,10 +6187,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5744,18 +6229,23 @@ class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ + DELETED = 'deleted' -class DeleteEnvironmentResponse(): +class DeleteEnvironmentResponse: """ Response object returned when deleting an environment. - :attr str environment_id: The unique identifier for the environment. - :attr str status: Status of the environment. + :param str environment_id: The unique identifier for the environment. + :param str status: Status of the environment. """ - def __init__(self, environment_id: str, status: str) -> None: + def __init__( + self, + environment_id: str, + status: str, + ) -> None: """ Initialize a DeleteEnvironmentResponse object. @@ -5769,14 +6259,14 @@ def __init__(self, environment_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id else: raise ValueError( 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' @@ -5819,23 +6309,26 @@ class StatusEnum(str, Enum): """ Status of the environment. """ + DELETED = 'deleted' -class DiskUsage(): +class DiskUsage: """ Summary of the disk usage statistics for the environment. - :attr int used_bytes: (optional) Number of bytes within the environment's disk + :param int used_bytes: (optional) Number of bytes within the environment's disk capacity that are currently used to store data. - :attr int maximum_allowed_bytes: (optional) Total number of bytes available in + :param int maximum_allowed_bytes: (optional) Total number of bytes available in the environment's disk capacity. """ - def __init__(self, - *, - used_bytes: int = None, - maximum_allowed_bytes: int = None) -> None: + def __init__( + self, + *, + used_bytes: Optional[int] = None, + maximum_allowed_bytes: Optional[int] = None, + ) -> None: """ Initialize a DiskUsage object. @@ -5847,10 +6340,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DiskUsage': """Initialize a DiskUsage object from a json dictionary.""" args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') - if 'maximum_allowed_bytes' in _dict: - args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') + if (used_bytes := _dict.get('used_bytes')) is not None: + args['used_bytes'] = used_bytes + if (maximum_allowed_bytes := + _dict.get('maximum_allowed_bytes')) is not None: + args['maximum_allowed_bytes'] = maximum_allowed_bytes return cls(**args) @classmethod @@ -5889,25 +6383,27 @@ def __ne__(self, other: 'DiskUsage') -> bool: return not self == other -class DocumentAccepted(): +class DocumentAccepted: """ Information returned after an uploaded document is accepted. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str status: (optional) Status of the document in the ingestion process. A + :param str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. - :attr List[Notice] notices: (optional) Array of notices produced by the + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, - *, - document_id: str = None, - status: str = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DocumentAccepted object. @@ -5928,14 +6424,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -5984,30 +6478,33 @@ class StatusEnum(str, Enum): returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ + PROCESSING = 'processing' PENDING = 'pending' -class DocumentCounts(): +class DocumentCounts: """ Object containing collection document count information. - :attr int available: (optional) The total number of available documents in the + :param int available: (optional) The total number of available documents in the collection. - :attr int processing: (optional) The number of documents in the collection that + :param int processing: (optional) The number of documents in the collection that are currently being processed. - :attr int failed: (optional) The number of documents in the collection that + :param int failed: (optional) The number of documents in the collection that failed to be ingested. - :attr int pending: (optional) The number of documents that have been uploaded to - the collection, but have not yet started processing. + :param int pending: (optional) The number of documents that have been uploaded + to the collection, but have not yet started processing. """ - def __init__(self, - *, - available: int = None, - processing: int = None, - failed: int = None, - pending: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + processing: Optional[int] = None, + failed: Optional[int] = None, + pending: Optional[int] = None, + ) -> None: """ Initialize a DocumentCounts object. @@ -6021,14 +6518,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentCounts': """Initialize a DocumentCounts object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'failed' in _dict: - args['failed'] = _dict.get('failed') - if 'pending' in _dict: - args['pending'] = _dict.get('pending') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (failed := _dict.get('failed')) is not None: + args['failed'] = failed + if (pending := _dict.get('pending')) is not None: + args['pending'] = pending return cls(**args) @classmethod @@ -6070,33 +6567,35 @@ def __ne__(self, other: 'DocumentCounts') -> bool: return not self == other -class DocumentStatus(): +class DocumentStatus: """ Status information about a submitted document. - :attr str document_id: (optional) The unique identifier of the document. - :attr str configuration_id: (optional) The unique identifier for the + :param str document_id: (optional) The unique identifier of the document. + :param str configuration_id: (optional) The unique identifier for the configuration. - :attr str status: (optional) Status of the document in the ingestion process. - :attr str status_description: (optional) Description of the document status. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices produced by the + :param str status: (optional) Status of the document in the ingestion process. + :param str status_description: (optional) Description of the document status. + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file. + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, - *, - document_id: str = None, - configuration_id: str = None, - status: str = None, - status_description: str = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + configuration_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha1: Optional[str] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DocumentStatus object. @@ -6119,24 +6618,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha1 := _dict.get('sha1')) is not None: + args['sha1'] = sha1 + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -6196,6 +6693,7 @@ class StatusEnum(str, Enum): """ Status of the document in the ingestion process. """ + AVAILABLE = 'available' AVAILABLE_WITH_NOTICES = 'available with notices' FAILED = 'failed' @@ -6206,50 +6704,53 @@ class FileTypeEnum(str, Enum): """ The type of the original source file. """ + PDF = 'pdf' HTML = 'html' WORD = 'word' JSON = 'json' -class Enrichment(): +class Enrichment: """ Enrichment step to perform on the document. Each enrichment is performed on the specified field in the order that they are listed in the configuration. - :attr str description: (optional) Describes what the enrichment step does. - :attr str destination_field: Field where enrichments will be stored. This field + :param str description: (optional) Describes what the enrichment step does. + :param str destination_field: Field where enrichments will be stored. This field must already exist or be at most 1 level deeper than an existing field. For example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but `text.foo.bar` is not. - :attr str source_field: Field to be enriched. + :param str source_field: Field to be enriched. Arrays can be specified as the **source_field** if the **enrichment** service for this enrichment is set to `natural_language_undstanding`. - :attr bool overwrite: (optional) Indicates that the enrichments will overwrite + :param bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. - :attr str enrichment: Name of the enrichment service to call. The only supported - option is `natural_language_understanding`. The `elements` option is deprecated - and support ended on 10 July 2020. + :param str enrichment: Name of the enrichment service to call. The only + supported option is `natural_language_understanding`. The `elements` option is + deprecated and support ended on 10 July 2020. The **options** object must contain Natural Language Understanding options. - :attr bool ignore_downstream_errors: (optional) If true, then most errors + :param bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. - :attr EnrichmentOptions options: (optional) Options that are specific to a + :param EnrichmentOptions options: (optional) Options that are specific to a particular enrichment. The `elements` enrichment type is deprecated. Use the [Create a project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the Discovery v2 API to create a `content_intelligence` project type instead. """ - def __init__(self, - destination_field: str, - source_field: str, - enrichment: str, - *, - description: str = None, - overwrite: bool = None, - ignore_downstream_errors: bool = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + destination_field: str, + source_field: str, + enrichment: str, + *, + description: Optional[str] = None, + overwrite: Optional[bool] = None, + ignore_downstream_errors: Optional[bool] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a Enrichment object. @@ -6290,33 +6791,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (destination_field := _dict.get('destination_field')) is not None: + args['destination_field'] = destination_field else: raise ValueError( 'Required property \'destination_field\' not present in Enrichment JSON' ) - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') + if (source_field := _dict.get('source_field')) is not None: + args['source_field'] = source_field else: raise ValueError( 'Required property \'source_field\' not present in Enrichment JSON' ) - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') - if 'enrichment' in _dict: - args['enrichment'] = _dict.get('enrichment') + if (overwrite := _dict.get('overwrite')) is not None: + args['overwrite'] = overwrite + if (enrichment := _dict.get('enrichment')) is not None: + args['enrichment'] = enrichment else: raise ValueError( 'Required property \'enrichment\' not present in Enrichment JSON' ) - if 'ignore_downstream_errors' in _dict: - args['ignore_downstream_errors'] = _dict.get( - 'ignore_downstream_errors') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (ignore_downstream_errors := + _dict.get('ignore_downstream_errors')) is not None: + args['ignore_downstream_errors'] = ignore_downstream_errors + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -6367,30 +6868,32 @@ def __ne__(self, other: 'Enrichment') -> bool: return not self == other -class EnrichmentOptions(): +class EnrichmentOptions: """ Options that are specific to a particular enrichment. The `elements` enrichment type is deprecated. Use the [Create a project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the Discovery v2 API to create a `content_intelligence` project type instead. - :attr NluEnrichmentFeatures features: (optional) Object containing Natural + :param NluEnrichmentFeatures features: (optional) Object containing Natural Language Understanding features to be used. - :attr str language: (optional) ISO 639-1 code indicating the language to use for - the analysis. This code overrides the automatic language detection performed by - the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` - (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and - `sv` (Swedish). **Note:** Not all features support all languages, automatic - detection is recommended. - :attr str model: (optional) Deprecated: The element extraction model to use, + :param str language: (optional) ISO 639-1 code indicating the language to use + for the analysis. This code overrides the automatic language detection performed + by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), + `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` + (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, + automatic detection is recommended. + :param str model: (optional) Deprecated: The element extraction model to use, which can be `contract` only. The `elements` enrichment is deprecated. """ - def __init__(self, - *, - features: 'NluEnrichmentFeatures' = None, - language: str = None, - model: str = None) -> None: + def __init__( + self, + *, + features: Optional['NluEnrichmentFeatures'] = None, + language: Optional[str] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a EnrichmentOptions object. @@ -6413,13 +6916,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = NluEnrichmentFeatures.from_dict( - _dict.get('features')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (features := _dict.get('features')) is not None: + args['features'] = NluEnrichmentFeatures.from_dict(features) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -6467,6 +6969,7 @@ class LanguageEnum(str, Enum): `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. """ + AR = 'ar' EN = 'en' FR = 'fr' @@ -6478,46 +6981,48 @@ class LanguageEnum(str, Enum): SV = 'sv' -class Environment(): +class Environment: """ Details about an environment. - :attr str environment_id: (optional) Unique identifier for the environment. - :attr str name: (optional) Name that identifies the environment. - :attr str description: (optional) Description of the environment. - :attr datetime created: (optional) Creation date of the environment, in the + :param str environment_id: (optional) Unique identifier for the environment. + :param str name: (optional) Name that identifies the environment. + :param str description: (optional) Description of the environment. + :param datetime created: (optional) Creation date of the environment, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date of most recent environment update, in + :param datetime updated: (optional) Date of most recent environment update, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr str status: (optional) Current status of the environment. `resizing` is + :param str status: (optional) Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. - :attr bool read_only: (optional) If `true`, the environment contains read-only + :param bool read_only: (optional) If `true`, the environment contains read-only collections that are maintained by IBM. - :attr str size: (optional) Current size of the environment. - :attr str requested_size: (optional) The new size requested for this + :param str size: (optional) Current size of the environment. + :param str requested_size: (optional) The new size requested for this environment. Only returned when the environment *status* is `resizing`. *Note:* Querying and indexing can still be performed during an environment upsize. - :attr IndexCapacity index_capacity: (optional) Details about the resource usage + :param IndexCapacity index_capacity: (optional) Details about the resource usage and capacity of the environment. - :attr SearchStatus search_status: (optional) Information about the Continuous + :param SearchStatus search_status: (optional) Information about the Continuous Relevancy Training for this environment. """ - def __init__(self, - *, - environment_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - read_only: bool = None, - size: str = None, - requested_size: str = None, - index_capacity: 'IndexCapacity' = None, - search_status: 'SearchStatus' = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + read_only: Optional[bool] = None, + size: Optional[str] = None, + requested_size: Optional[str] = None, + index_capacity: Optional['IndexCapacity'] = None, + search_status: Optional['SearchStatus'] = None, + ) -> None: """ Initialize a Environment object. @@ -6549,30 +7054,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'read_only' in _dict: - args['read_only'] = _dict.get('read_only') - if 'size' in _dict: - args['size'] = _dict.get('size') - if 'requested_size' in _dict: - args['requested_size'] = _dict.get('requested_size') - if 'index_capacity' in _dict: - args['index_capacity'] = IndexCapacity.from_dict( - _dict.get('index_capacity')) - if 'search_status' in _dict: - args['search_status'] = SearchStatus.from_dict( - _dict.get('search_status')) + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (read_only := _dict.get('read_only')) is not None: + args['read_only'] = read_only + if (size := _dict.get('size')) is not None: + args['size'] = size + if (requested_size := _dict.get('requested_size')) is not None: + args['requested_size'] = requested_size + if (index_capacity := _dict.get('index_capacity')) is not None: + args['index_capacity'] = IndexCapacity.from_dict(index_capacity) + if (search_status := _dict.get('search_status')) is not None: + args['search_status'] = SearchStatus.from_dict(search_status) return cls(**args) @classmethod @@ -6639,6 +7142,7 @@ class StatusEnum(str, Enum): increase the environment size has been made, but is still in the process of being completed. """ + ACTIVE = 'active' PENDING = 'pending' MAINTENANCE = 'maintenance' @@ -6648,6 +7152,7 @@ class SizeEnum(str, Enum): """ Current size of the environment. """ + LT = 'LT' XS = 'XS' S = 'S' @@ -6660,19 +7165,22 @@ class SizeEnum(str, Enum): XXXL = 'XXXL' -class EnvironmentDocuments(): +class EnvironmentDocuments: """ Summary of the document usage statistics for the environment. - :attr int available: (optional) Number of documents indexed for the environment. - :attr int maximum_allowed: (optional) Total number of documents allowed in the + :param int available: (optional) Number of documents indexed for the + environment. + :param int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a EnvironmentDocuments object. @@ -6684,10 +7192,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -6725,36 +7233,39 @@ def __ne__(self, other: 'EnvironmentDocuments') -> bool: return not self == other -class EventData(): +class EventData: """ Query event data object. - :attr str environment_id: The **environment_id** associated with the query that + :param str environment_id: The **environment_id** associated with the query that the event is associated with. - :attr str session_token: The session token that was returned as part of the + :param str session_token: The session token that was returned as part of the query results that this event is associated with. - :attr datetime client_timestamp: (optional) The optional timestamp for the event - that was created. If not provided, the time that the event was created in the - log was used. - :attr int display_rank: (optional) The rank of the result item which the event + :param datetime client_timestamp: (optional) The optional timestamp for the + event that was created. If not provided, the time that the event was created in + the log was used. + :param int display_rank: (optional) The rank of the result item which the event is associated with. - :attr str collection_id: The **collection_id** of the document that this event + :param str collection_id: The **collection_id** of the document that this event is associated with. - :attr str document_id: The **document_id** of the document that this event is + :param str document_id: The **document_id** of the document that this event is associated with. - :attr str query_id: (optional) The query identifier stored in the log. The query - and any events associated with that query are stored with the same **query_id**. + :param str query_id: (optional) The query identifier stored in the log. The + query and any events associated with that query are stored with the same + **query_id**. """ - def __init__(self, - environment_id: str, - session_token: str, - collection_id: str, - document_id: str, - *, - client_timestamp: datetime = None, - display_rank: int = None, - query_id: str = None) -> None: + def __init__( + self, + environment_id: str, + session_token: str, + collection_id: str, + document_id: str, + *, + client_timestamp: Optional[datetime] = None, + display_rank: Optional[int] = None, + query_id: Optional[str] = None, + ) -> None: """ Initialize a EventData object. @@ -6784,37 +7295,36 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EventData': """Initialize a EventData object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id else: raise ValueError( 'Required property \'environment_id\' not present in EventData JSON' ) - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token else: raise ValueError( 'Required property \'session_token\' not present in EventData JSON' ) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (client_timestamp := _dict.get('client_timestamp')) is not None: + args['client_timestamp'] = string_to_datetime(client_timestamp) + if (display_rank := _dict.get('display_rank')) is not None: + args['display_rank'] = display_rank + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in EventData JSON' ) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in EventData JSON' ) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id return cls(**args) @classmethod @@ -6862,23 +7372,25 @@ def __ne__(self, other: 'EventData') -> bool: return not self == other -class Expansion(): +class Expansion: """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions for the word `cold` in another. - :attr List[str] input_terms: (optional) A list of terms that will be expanded + :param List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. - :attr List[str] expanded_terms: A list of terms that this expansion will be + :param List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. """ - def __init__(self, - expanded_terms: List[str], - *, - input_terms: List[str] = None) -> None: + def __init__( + self, + expanded_terms: List[str], + *, + input_terms: Optional[List[str]] = None, + ) -> None: """ Initialize a Expansion object. @@ -6896,10 +7408,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} - if 'input_terms' in _dict: - args['input_terms'] = _dict.get('input_terms') - if 'expanded_terms' in _dict: - args['expanded_terms'] = _dict.get('expanded_terms') + if (input_terms := _dict.get('input_terms')) is not None: + args['input_terms'] = input_terms + if (expanded_terms := _dict.get('expanded_terms')) is not None: + args['expanded_terms'] = expanded_terms else: raise ValueError( 'Required property \'expanded_terms\' not present in Expansion JSON' @@ -6939,11 +7451,11 @@ def __ne__(self, other: 'Expansion') -> bool: return not self == other -class Expansions(): +class Expansions: """ The query expansion definitions for the specified collection. - :attr List[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded @@ -6958,7 +7470,10 @@ class Expansions(): **expanded_terms** array. """ - def __init__(self, expansions: List['Expansion']) -> None: + def __init__( + self, + expansions: List['Expansion'], + ) -> None: """ Initialize a Expansions object. @@ -6982,10 +7497,8 @@ def __init__(self, expansions: List['Expansion']) -> None: def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} - if 'expansions' in _dict: - args['expansions'] = [ - Expansion.from_dict(v) for v in _dict.get('expansions') - ] + if (expansions := _dict.get('expansions')) is not None: + args['expansions'] = [Expansion.from_dict(v) for v in expansions] else: raise ValueError( 'Required property \'expansions\' not present in Expansions JSON' @@ -7029,15 +7542,20 @@ def __ne__(self, other: 'Expansions') -> bool: return not self == other -class Field(): +class Field: """ Object containing field details. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. """ - def __init__(self, *, field: str = None, type: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a Field object. @@ -7049,10 +7567,10 @@ def __init__(self, *, field: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (field := _dict.get('field')) is not None: + args['field'] = field + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -7091,6 +7609,7 @@ class TypeEnum(str, Enum): """ The type of the field. """ + NESTED = 'nested' STRING = 'string' DATE = 'date' @@ -7104,27 +7623,29 @@ class TypeEnum(str, Enum): BINARY = 'binary' -class FontSetting(): +class FontSetting: """ Font matching configuration. - :attr int level: (optional) The HTML heading level that any content with the + :param int level: (optional) The HTML heading level that any content with the matching font is converted to. - :attr int min_size: (optional) The minimum size of the font to match. - :attr int max_size: (optional) The maximum size of the font to match. - :attr bool bold: (optional) When `true`, the font is matched if it is bold. - :attr bool italic: (optional) When `true`, the font is matched if it is italic. - :attr str name: (optional) The name of the font. - """ - - def __init__(self, - *, - level: int = None, - min_size: int = None, - max_size: int = None, - bold: bool = None, - italic: bool = None, - name: str = None) -> None: + :param int min_size: (optional) The minimum size of the font to match. + :param int max_size: (optional) The maximum size of the font to match. + :param bool bold: (optional) When `true`, the font is matched if it is bold. + :param bool italic: (optional) When `true`, the font is matched if it is italic. + :param str name: (optional) The name of the font. + """ + + def __init__( + self, + *, + level: Optional[int] = None, + min_size: Optional[int] = None, + max_size: Optional[int] = None, + bold: Optional[bool] = None, + italic: Optional[bool] = None, + name: Optional[str] = None, + ) -> None: """ Initialize a FontSetting object. @@ -7149,18 +7670,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FontSetting': """Initialize a FontSetting object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'min_size' in _dict: - args['min_size'] = _dict.get('min_size') - if 'max_size' in _dict: - args['max_size'] = _dict.get('max_size') - if 'bold' in _dict: - args['bold'] = _dict.get('bold') - if 'italic' in _dict: - args['italic'] = _dict.get('italic') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (level := _dict.get('level')) is not None: + args['level'] = level + if (min_size := _dict.get('min_size')) is not None: + args['min_size'] = min_size + if (max_size := _dict.get('max_size')) is not None: + args['max_size'] = max_size + if (bold := _dict.get('bold')) is not None: + args['bold'] = bold + if (italic := _dict.get('italic')) is not None: + args['italic'] = italic + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -7204,28 +7725,30 @@ def __ne__(self, other: 'FontSetting') -> bool: return not self == other -class Gateway(): +class Gateway: """ Object describing a specific gateway. - :attr str gateway_id: (optional) The gateway ID of the gateway. - :attr str name: (optional) The user defined name of the gateway. - :attr str status: (optional) The current status of the gateway. `connected` + :param str gateway_id: (optional) The gateway ID of the gateway. + :param str name: (optional) The user defined name of the gateway. + :param str status: (optional) The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. - :attr str token: (optional) The generated **token** for this gateway. The value + :param str token: (optional) The generated **token** for this gateway. The value of this field is used when configuring the remotly installed gateway. - :attr str token_id: (optional) The generated **token_id** for this gateway. The + :param str token_id: (optional) The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed gateway. """ - def __init__(self, - *, - gateway_id: str = None, - name: str = None, - status: str = None, - token: str = None, - token_id: str = None) -> None: + def __init__( + self, + *, + gateway_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[str] = None, + token: Optional[str] = None, + token_id: Optional[str] = None, + ) -> None: """ Initialize a Gateway object. @@ -7250,16 +7773,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Gateway': """Initialize a Gateway object from a json dictionary.""" args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'token' in _dict: - args['token'] = _dict.get('token') - if 'token_id' in _dict: - args['token_id'] = _dict.get('token_id') + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (token := _dict.get('token')) is not None: + args['token'] = token + if (token_id := _dict.get('token_id')) is not None: + args['token_id'] = token_id return cls(**args) @classmethod @@ -7305,19 +7828,25 @@ class StatusEnum(str, Enum): The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. """ + CONNECTED = 'connected' IDLE = 'idle' -class GatewayDelete(): +class GatewayDelete: """ Gatway deletion confirmation. - :attr str gateway_id: (optional) The gateway ID of the deleted gateway. - :attr str status: (optional) The status of the request. + :param str gateway_id: (optional) The gateway ID of the deleted gateway. + :param str status: (optional) The status of the request. """ - def __init__(self, *, gateway_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + gateway_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a GatewayDelete object. @@ -7331,10 +7860,10 @@ def __init__(self, *, gateway_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayDelete': """Initialize a GatewayDelete object from a json dictionary.""" args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -7370,15 +7899,19 @@ def __ne__(self, other: 'GatewayDelete') -> bool: return not self == other -class GatewayList(): +class GatewayList: """ Object containing gateways array. - :attr List[Gateway] gateways: (optional) Array of configured gateway + :param List[Gateway] gateways: (optional) Array of configured gateway connections. """ - def __init__(self, *, gateways: List['Gateway'] = None) -> None: + def __init__( + self, + *, + gateways: Optional[List['Gateway']] = None, + ) -> None: """ Initialize a GatewayList object. @@ -7391,10 +7924,8 @@ def __init__(self, *, gateways: List['Gateway'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayList': """Initialize a GatewayList object from a json dictionary.""" args = {} - if 'gateways' in _dict: - args['gateways'] = [ - Gateway.from_dict(v) for v in _dict.get('gateways') - ] + if (gateways := _dict.get('gateways')) is not None: + args['gateways'] = [Gateway.from_dict(v) for v in gateways] return cls(**args) @classmethod @@ -7434,32 +7965,34 @@ def __ne__(self, other: 'GatewayList') -> bool: return not self == other -class HtmlSettings(): +class HtmlSettings: """ A list of HTML conversion settings. - :attr List[str] exclude_tags_completely: (optional) Array of HTML tags that are + :param List[str] exclude_tags_completely: (optional) Array of HTML tags that are excluded completely. - :attr List[str] exclude_tags_keep_content: (optional) Array of HTML tags which + :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. - :attr XPathPatterns keep_content: (optional) Object containing an array of + :param XPathPatterns keep_content: (optional) Object containing an array of XPaths. - :attr XPathPatterns exclude_content: (optional) Object containing an array of + :param XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :attr List[str] keep_tag_attributes: (optional) An array of HTML tag attributes + :param List[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. - :attr List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes + :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ - def __init__(self, - *, - exclude_tags_completely: List[str] = None, - exclude_tags_keep_content: List[str] = None, - keep_content: 'XPathPatterns' = None, - exclude_content: 'XPathPatterns' = None, - keep_tag_attributes: List[str] = None, - exclude_tag_attributes: List[str] = None) -> None: + def __init__( + self, + *, + exclude_tags_completely: Optional[List[str]] = None, + exclude_tags_keep_content: Optional[List[str]] = None, + keep_content: Optional['XPathPatterns'] = None, + exclude_content: Optional['XPathPatterns'] = None, + keep_tag_attributes: Optional[List[str]] = None, + exclude_tag_attributes: Optional[List[str]] = None, + ) -> None: """ Initialize a HtmlSettings object. @@ -7487,22 +8020,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'HtmlSettings': """Initialize a HtmlSettings object from a json dictionary.""" args = {} - if 'exclude_tags_completely' in _dict: - args['exclude_tags_completely'] = _dict.get( - 'exclude_tags_completely') - if 'exclude_tags_keep_content' in _dict: - args['exclude_tags_keep_content'] = _dict.get( - 'exclude_tags_keep_content') - if 'keep_content' in _dict: - args['keep_content'] = XPathPatterns.from_dict( - _dict.get('keep_content')) - if 'exclude_content' in _dict: - args['exclude_content'] = XPathPatterns.from_dict( - _dict.get('exclude_content')) - if 'keep_tag_attributes' in _dict: - args['keep_tag_attributes'] = _dict.get('keep_tag_attributes') - if 'exclude_tag_attributes' in _dict: - args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') + if (exclude_tags_completely := + _dict.get('exclude_tags_completely')) is not None: + args['exclude_tags_completely'] = exclude_tags_completely + if (exclude_tags_keep_content := + _dict.get('exclude_tags_keep_content')) is not None: + args['exclude_tags_keep_content'] = exclude_tags_keep_content + if (keep_content := _dict.get('keep_content')) is not None: + args['keep_content'] = XPathPatterns.from_dict(keep_content) + if (exclude_content := _dict.get('exclude_content')) is not None: + args['exclude_content'] = XPathPatterns.from_dict(exclude_content) + if (keep_tag_attributes := + _dict.get('keep_tag_attributes')) is not None: + args['keep_tag_attributes'] = keep_tag_attributes + if (exclude_tag_attributes := + _dict.get('exclude_tag_attributes')) is not None: + args['exclude_tag_attributes'] = exclude_tag_attributes return cls(**args) @classmethod @@ -7558,23 +8091,25 @@ def __ne__(self, other: 'HtmlSettings') -> bool: return not self == other -class IndexCapacity(): +class IndexCapacity: """ Details about the resource usage and capacity of the environment. - :attr EnvironmentDocuments documents: (optional) Summary of the document usage + :param EnvironmentDocuments documents: (optional) Summary of the document usage statistics for the environment. - :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :attr CollectionUsage collections: (optional) Summary of the collection usage in + :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for the environment. + :param CollectionUsage collections: (optional) Summary of the collection usage + in the environment. """ - def __init__(self, - *, - documents: 'EnvironmentDocuments' = None, - disk_usage: 'DiskUsage' = None, - collections: 'CollectionUsage' = None) -> None: + def __init__( + self, + *, + documents: Optional['EnvironmentDocuments'] = None, + disk_usage: Optional['DiskUsage'] = None, + collections: Optional['CollectionUsage'] = None, + ) -> None: """ Initialize a IndexCapacity object. @@ -7593,14 +8128,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'IndexCapacity': """Initialize a IndexCapacity object from a json dictionary.""" args = {} - if 'documents' in _dict: - args['documents'] = EnvironmentDocuments.from_dict( - _dict.get('documents')) - if 'disk_usage' in _dict: - args['disk_usage'] = DiskUsage.from_dict(_dict.get('disk_usage')) - if 'collections' in _dict: - args['collections'] = CollectionUsage.from_dict( - _dict.get('collections')) + if (documents := _dict.get('documents')) is not None: + args['documents'] = EnvironmentDocuments.from_dict(documents) + if (disk_usage := _dict.get('disk_usage')) is not None: + args['disk_usage'] = DiskUsage.from_dict(disk_usage) + if (collections := _dict.get('collections')) is not None: + args['collections'] = CollectionUsage.from_dict(collections) return cls(**args) @classmethod @@ -7647,7 +8180,7 @@ def __ne__(self, other: 'IndexCapacity') -> bool: return not self == other -class ListCollectionFieldsResponse(): +class ListCollectionFieldsResponse: """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -7660,11 +8193,15 @@ class ListCollectionFieldsResponse(): `v{N}-fullnews-t3-{YEAR}.mappings` (for example, `v5-fullnews-t3-2016.mappings.text.properties.author`). - :attr List[Field] fields: (optional) An array containing information about each + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__( + self, + *, + fields: Optional[List['Field']] = None, + ) -> None: """ Initialize a ListCollectionFieldsResponse object. @@ -7677,8 +8214,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] + if (fields := _dict.get('fields')) is not None: + args['fields'] = [Field.from_dict(v) for v in fields] return cls(**args) @classmethod @@ -7718,15 +8255,19 @@ def __ne__(self, other: 'ListCollectionFieldsResponse') -> bool: return not self == other -class ListCollectionsResponse(): +class ListCollectionsResponse: """ Response object containing an array of collection details. - :attr List[Collection] collections: (optional) An array containing information + :param List[Collection] collections: (optional) An array containing information about each collection in the environment. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: + def __init__( + self, + *, + collections: Optional[List['Collection']] = None, + ) -> None: """ Initialize a ListCollectionsResponse object. @@ -7739,10 +8280,8 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(v) for v in _dict.get('collections') - ] + if (collections := _dict.get('collections')) is not None: + args['collections'] = [Collection.from_dict(v) for v in collections] return cls(**args) @classmethod @@ -7782,15 +8321,19 @@ def __ne__(self, other: 'ListCollectionsResponse') -> bool: return not self == other -class ListConfigurationsResponse(): +class ListConfigurationsResponse: """ Object containing an array of available configurations. - :attr List[Configuration] configurations: (optional) An array of configurations + :param List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ - def __init__(self, *, configurations: List['Configuration'] = None) -> None: + def __init__( + self, + *, + configurations: Optional[List['Configuration']] = None, + ) -> None: """ Initialize a ListConfigurationsResponse object. @@ -7803,9 +8346,9 @@ def __init__(self, *, configurations: List['Configuration'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} - if 'configurations' in _dict: + if (configurations := _dict.get('configurations')) is not None: args['configurations'] = [ - Configuration.from_dict(v) for v in _dict.get('configurations') + Configuration.from_dict(v) for v in configurations ] return cls(**args) @@ -7846,15 +8389,19 @@ def __ne__(self, other: 'ListConfigurationsResponse') -> bool: return not self == other -class ListEnvironmentsResponse(): +class ListEnvironmentsResponse: """ Response object containing an array of configured environments. - :attr List[Environment] environments: (optional) An array of [environments] that - are available for the service instance. + :param List[Environment] environments: (optional) An array of [environments] + that are available for the service instance. """ - def __init__(self, *, environments: List['Environment'] = None) -> None: + def __init__( + self, + *, + environments: Optional[List['Environment']] = None, + ) -> None: """ Initialize a ListEnvironmentsResponse object. @@ -7867,9 +8414,9 @@ def __init__(self, *, environments: List['Environment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} - if 'environments' in _dict: + if (environments := _dict.get('environments')) is not None: args['environments'] = [ - Environment.from_dict(v) for v in _dict.get('environments') + Environment.from_dict(v) for v in environments ] return cls(**args) @@ -7910,19 +8457,21 @@ def __ne__(self, other: 'ListEnvironmentsResponse') -> bool: return not self == other -class LogQueryResponse(): +class LogQueryResponse: """ Object containing results that match the requested **logs** query. - :attr int matching_results: (optional) Number of matching results. - :attr List[LogQueryResponseResult] results: (optional) Array of log query + :param int matching_results: (optional) Number of matching results. + :param List[LogQueryResponseResult] results: (optional) Array of log query response results. """ - def __init__(self, - *, - matching_results: int = None, - results: List['LogQueryResponseResult'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['LogQueryResponseResult']] = None, + ) -> None: """ Initialize a LogQueryResponse object. @@ -7937,12 +8486,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': """Initialize a LogQueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: args['results'] = [ - LogQueryResponseResult.from_dict(v) - for v in _dict.get('results') + LogQueryResponseResult.from_dict(v) for v in results ] return cls(**args) @@ -7986,40 +8534,40 @@ def __ne__(self, other: 'LogQueryResponse') -> bool: return not self == other -class LogQueryResponseResult(): +class LogQueryResponseResult: """ Individual result object for a **logs** query. Each object represents either a query to a Discovery collection or an event that is associated with a query. - :attr str environment_id: (optional) The environment ID that is associated with + :param str environment_id: (optional) The environment ID that is associated with this log entry. - :attr str customer_id: (optional) The **customer_id** label that was specified + :param str customer_id: (optional) The **customer_id** label that was specified in the header of the query or event API call that corresponds to this log entry. - :attr str document_type: (optional) The type of log entry returned. + :param str document_type: (optional) The type of log entry returned. **query** indicates that the log represents the results of a call to the single collection **query** method. **event** indicates that the log represents a call to the **events** API. - :attr str natural_language_query: (optional) The value of the + :param str natural_language_query: (optional) The value of the **natural_language_query** query parameter that was used to create these results. Only returned with logs of type **query**. **Note:** Other query parameters (such as **filter** or **deduplicate**) might have been used with this query, but are not recorded. - :attr LogQueryResponseResultDocuments document_results: (optional) Object + :param LogQueryResponseResultDocuments document_results: (optional) Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr datetime created_timestamp: (optional) Date that the log result was + :param datetime created_timestamp: (optional) Date that the log result was created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :attr datetime client_timestamp: (optional) Date specified by the user when + :param datetime client_timestamp: (optional) Date specified by the user when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with logs of type **event**. - :attr str query_id: (optional) Identifier that corresponds to the + :param str query_id: (optional) Identifier that corresponds to the **natural_language_query** string used in the original or associated query. All **event** and **query** log entries that have the same original **natural_language_query** string also have them same **query_id**. This field can be used to recall all **event** and **query** log results that have the same original query (**event** logs do not contain the original **natural_language_query** field). - :attr str session_token: (optional) Unique identifier (within a 24-hour period) + :param str session_token: (optional) Unique identifier (within a 24-hour period) that identifies a single `query` log and any `event` logs that were created for it. **Note:** If the exact same query is run at the exact same time on different @@ -8028,36 +8576,38 @@ class LogQueryResponseResult(): **Note:** Session tokens are case sensitive. To avoid matching on session tokens that are identical except for case, use the exact match operator (`::`) when you query for a specific session token. - :attr str collection_id: (optional) The collection ID of the document associated - with this event. Only returned with logs of type `event`. - :attr int display_rank: (optional) The original display rank of the document + :param str collection_id: (optional) The collection ID of the document + associated with this event. Only returned with logs of type `event`. + :param int display_rank: (optional) The original display rank of the document associated with this event. Only returned with logs of type `event`. - :attr str document_id: (optional) The document ID of the document associated + :param str document_id: (optional) The document ID of the document associated with this event. Only returned with logs of type `event`. - :attr str event_type: (optional) The type of event that this object respresents. - Possible values are + :param str event_type: (optional) The type of event that this object + respresents. Possible values are - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. - :attr str result_type: (optional) The type of result that this **event** is + :param str result_type: (optional) The type of result that this **event** is associated with. Only returned with logs of type `event`. """ - def __init__(self, - *, - environment_id: str = None, - customer_id: str = None, - document_type: str = None, - natural_language_query: str = None, - document_results: 'LogQueryResponseResultDocuments' = None, - created_timestamp: datetime = None, - client_timestamp: datetime = None, - query_id: str = None, - session_token: str = None, - collection_id: str = None, - display_rank: int = None, - document_id: str = None, - event_type: str = None, - result_type: str = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + customer_id: Optional[str] = None, + document_type: Optional[str] = None, + natural_language_query: Optional[str] = None, + document_results: Optional['LogQueryResponseResultDocuments'] = None, + created_timestamp: Optional[datetime] = None, + client_timestamp: Optional[datetime] = None, + query_id: Optional[str] = None, + session_token: Optional[str] = None, + collection_id: Optional[str] = None, + display_rank: Optional[int] = None, + document_id: Optional[str] = None, + event_type: Optional[str] = None, + result_type: Optional[str] = None, + ) -> None: """ Initialize a LogQueryResponseResult object. @@ -8132,38 +8682,37 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') - if 'document_type' in _dict: - args['document_type'] = _dict.get('document_type') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'document_results' in _dict: + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id + if (document_type := _dict.get('document_type')) is not None: + args['document_type'] = document_type + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query + if (document_results := _dict.get('document_results')) is not None: args[ 'document_results'] = LogQueryResponseResultDocuments.from_dict( - _dict.get('document_results')) - if 'created_timestamp' in _dict: - args['created_timestamp'] = string_to_datetime( - _dict.get('created_timestamp')) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'result_type' in _dict: - args['result_type'] = _dict.get('result_type') + document_results) + if (created_timestamp := _dict.get('created_timestamp')) is not None: + args['created_timestamp'] = string_to_datetime(created_timestamp) + if (client_timestamp := _dict.get('client_timestamp')) is not None: + args['client_timestamp'] = string_to_datetime(client_timestamp) + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (display_rank := _dict.get('display_rank')) is not None: + args['display_rank'] = display_rank + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (result_type := _dict.get('result_type')) is not None: + args['result_type'] = result_type return cls(**args) @classmethod @@ -8238,6 +8787,7 @@ class DocumentTypeEnum(str, Enum): collection **query** method. **event** indicates that the log represents a call to the **events** API. """ + QUERY = 'query' EVENT = 'event' @@ -8247,6 +8797,7 @@ class EventTypeEnum(str, Enum): - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. """ + CLICK = 'click' QUERY = 'query' @@ -8255,24 +8806,27 @@ class ResultTypeEnum(str, Enum): The type of result that this **event** is associated with. Only returned with logs of type `event`. """ + DOCUMENT = 'document' -class LogQueryResponseResultDocuments(): +class LogQueryResponseResultDocuments: """ Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr List[LogQueryResponseResultDocumentsResult] results: (optional) Array of + :param List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. - :attr int count: (optional) The number of results returned in the query + :param int count: (optional) The number of results returned in the query associate with this log. """ - def __init__(self, - *, - results: List['LogQueryResponseResultDocumentsResult'] = None, - count: int = None) -> None: + def __init__( + self, + *, + results: Optional[List['LogQueryResponseResultDocumentsResult']] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a LogQueryResponseResultDocuments object. @@ -8288,13 +8842,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} - if 'results' in _dict: + if (results := _dict.get('results')) is not None: args['results'] = [ LogQueryResponseResultDocumentsResult.from_dict(v) - for v in _dict.get('results') + for v in results ] - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8336,30 +8890,32 @@ def __ne__(self, other: 'LogQueryResponseResultDocuments') -> bool: return not self == other -class LogQueryResponseResultDocumentsResult(): +class LogQueryResponseResultDocumentsResult: """ Each object in the **results** array corresponds to an individual document returned by the original query. - :attr int position: (optional) The result rank of this document. A position of + :param int position: (optional) The result rank of this document. A position of `1` indicates that it was the first returned result. - :attr str document_id: (optional) The **document_id** of the document that this + :param str document_id: (optional) The **document_id** of the document that this result represents. - :attr float score: (optional) The raw score of this result. A higher score + :param float score: (optional) The raw score of this result. A higher score indicates a greater match to the query parameters. - :attr float confidence: (optional) The confidence score of the result's + :param float confidence: (optional) The confidence score of the result's analysis. A higher score indicating greater confidence. - :attr str collection_id: (optional) The **collection_id** of the document + :param str collection_id: (optional) The **collection_id** of the document represented by this result. """ - def __init__(self, - *, - position: int = None, - document_id: str = None, - score: float = None, - confidence: float = None, - collection_id: str = None) -> None: + def __init__( + self, + *, + position: Optional[int] = None, + document_id: Optional[str] = None, + score: Optional[float] = None, + confidence: Optional[float] = None, + collection_id: Optional[str] = None, + ) -> None: """ Initialize a LogQueryResponseResultDocumentsResult object. @@ -8384,16 +8940,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} - if 'position' in _dict: - args['position'] = _dict.get('position') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (position := _dict.get('position')) is not None: + args['position'] = position + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (score := _dict.get('score')) is not None: + args['score'] = score + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id return cls(**args) @classmethod @@ -8435,23 +8991,25 @@ def __ne__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: return not self == other -class MetricAggregation(): +class MetricAggregation: """ An aggregation analyzing log information for queries and events. - :attr str interval: (optional) The measurement interval for this metric. Metric + :param str interval: (optional) The measurement interval for this metric. Metric intervals are always 1 day (`1d`). - :attr str event_type: (optional) The event type associated with this metric + :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr List[MetricAggregationResult] results: (optional) Array of metric + :param List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ - def __init__(self, - *, - interval: str = None, - event_type: str = None, - results: List['MetricAggregationResult'] = None) -> None: + def __init__( + self, + *, + interval: Optional[str] = None, + event_type: Optional[str] = None, + results: Optional[List['MetricAggregationResult']] = None, + ) -> None: """ Initialize a MetricAggregation object. @@ -8470,14 +9028,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregation': """Initialize a MetricAggregation object from a json dictionary.""" args = {} - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (results := _dict.get('results')) is not None: args['results'] = [ - MetricAggregationResult.from_dict(v) - for v in _dict.get('results') + MetricAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -8522,26 +9079,28 @@ def __ne__(self, other: 'MetricAggregation') -> bool: return not self == other -class MetricAggregationResult(): +class MetricAggregationResult: """ Aggregation result data for the requested metric. - :attr datetime key_as_string: (optional) Date in string form representing the + :param datetime key_as_string: (optional) Date in string form representing the start of this interval. - :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, + :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, that represents the start of this interval. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events + :param int matching_results: (optional) Number of matching results. + :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries for the interval. Only returned with **event_rate** metrics. """ - def __init__(self, - *, - key_as_string: datetime = None, - key: int = None, - matching_results: int = None, - event_rate: float = None) -> None: + def __init__( + self, + *, + key_as_string: Optional[datetime] = None, + key: Optional[int] = None, + matching_results: Optional[int] = None, + event_rate: Optional[float] = None, + ) -> None: """ Initialize a MetricAggregationResult object. @@ -8563,15 +9122,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = string_to_datetime( - _dict.get('key_as_string')) - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = string_to_datetime(key_as_string) + if (key := _dict.get('key')) is not None: + args['key'] = key + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (event_rate := _dict.get('event_rate')) is not None: + args['event_rate'] = event_rate return cls(**args) @classmethod @@ -8612,17 +9170,19 @@ def __ne__(self, other: 'MetricAggregationResult') -> bool: return not self == other -class MetricResponse(): +class MetricResponse: """ The response generated from a call to a **metrics** method. - :attr List[MetricAggregation] aggregations: (optional) Array of metric + :param List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ - def __init__(self, - *, - aggregations: List['MetricAggregation'] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List['MetricAggregation']] = None, + ) -> None: """ Initialize a MetricResponse object. @@ -8635,10 +9195,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricResponse': """Initialize a MetricResponse object from a json dictionary.""" args = {} - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - MetricAggregation.from_dict(v) - for v in _dict.get('aggregations') + MetricAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -8679,20 +9238,22 @@ def __ne__(self, other: 'MetricResponse') -> bool: return not self == other -class MetricTokenAggregation(): +class MetricTokenAggregation: """ An aggregation analyzing log information for queries and events. - :attr str event_type: (optional) The event type associated with this metric + :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr List[MetricTokenAggregationResult] results: (optional) Array of results + :param List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ - def __init__(self, - *, - event_type: str = None, - results: List['MetricTokenAggregationResult'] = None) -> None: + def __init__( + self, + *, + event_type: Optional[str] = None, + results: Optional[List['MetricTokenAggregationResult']] = None, + ) -> None: """ Initialize a MetricTokenAggregation object. @@ -8708,12 +9269,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (results := _dict.get('results')) is not None: args['results'] = [ - MetricTokenAggregationResult.from_dict(v) - for v in _dict.get('results') + MetricTokenAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -8756,23 +9316,25 @@ def __ne__(self, other: 'MetricTokenAggregation') -> bool: return not self == other -class MetricTokenAggregationResult(): +class MetricTokenAggregationResult: """ Aggregation result data for the requested metric. - :attr str key: (optional) The content of the **natural_language_query** + :param str key: (optional) The content of the **natural_language_query** parameter used in the query that this result represents. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events + :param int matching_results: (optional) Number of matching results. + :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries currently stored (queries and events are stored in the log for 30 days). """ - def __init__(self, - *, - key: str = None, - matching_results: int = None, - event_rate: float = None) -> None: + def __init__( + self, + *, + key: Optional[str] = None, + matching_results: Optional[int] = None, + event_rate: Optional[float] = None, + ) -> None: """ Initialize a MetricTokenAggregationResult object. @@ -8791,12 +9353,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') + if (key := _dict.get('key')) is not None: + args['key'] = key + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (event_rate := _dict.get('event_rate')) is not None: + args['event_rate'] = event_rate return cls(**args) @classmethod @@ -8835,17 +9397,19 @@ def __ne__(self, other: 'MetricTokenAggregationResult') -> bool: return not self == other -class MetricTokenResponse(): +class MetricTokenResponse: """ The response generated from a call to a **metrics** method that evaluates tokens. - :attr List[MetricTokenAggregation] aggregations: (optional) Array of metric + :param List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ - def __init__(self, - *, - aggregations: List['MetricTokenAggregation'] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List['MetricTokenAggregation']] = None, + ) -> None: """ Initialize a MetricTokenResponse object. @@ -8858,10 +9422,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - MetricTokenAggregation.from_dict(v) - for v in _dict.get('aggregations') + MetricTokenAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -8902,15 +9465,19 @@ def __ne__(self, other: 'MetricTokenResponse') -> bool: return not self == other -class NluEnrichmentConcepts(): +class NluEnrichmentConcepts: """ An object specifiying the concepts enrichment and related parameters. - :attr int limit: (optional) The maximum number of concepts enrichments to extact - from each instance of the specified field. + :param int limit: (optional) The maximum number of concepts enrichments to + extact from each instance of the specified field. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentConcepts object. @@ -8923,8 +9490,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -8958,20 +9525,22 @@ def __ne__(self, other: 'NluEnrichmentConcepts') -> bool: return not self == other -class NluEnrichmentEmotion(): +class NluEnrichmentEmotion: """ An object specifying the emotion detection enrichment and related parameters. - :attr bool document: (optional) When `true`, emotion detection is performed on + :param bool document: (optional) When `true`, emotion detection is performed on the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a NluEnrichmentEmotion object. @@ -8987,10 +9556,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -9026,37 +9595,39 @@ def __ne__(self, other: 'NluEnrichmentEmotion') -> bool: return not self == other -class NluEnrichmentEntities(): +class NluEnrichmentEntities: """ An object speficying the Entities enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of entities + :param bool sentiment: (optional) When `true`, sentiment analysis of entities will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of entities will + :param bool emotion: (optional) When `true`, emotion detection of entities will be performed on the specified field. - :attr int limit: (optional) The maximum number of entities to extract for each + :param int limit: (optional) The maximum number of entities to extract for each instance of the specified field. - :attr bool mentions: (optional) When `true`, the number of mentions of each + :param bool mentions: (optional) When `true`, the number of mentions of each identified entity is recorded. The default is `false`. - :attr bool mention_types: (optional) When `true`, the types of mentions for each - idetifieid entity is recorded. The default is `false`. - :attr bool sentence_locations: (optional) When `true`, a list of sentence + :param bool mention_types: (optional) When `true`, the types of mentions for + each idetifieid entity is recorded. The default is `false`. + :param bool sentence_locations: (optional) When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. - :attr str model: (optional) The enrichement model to use with entity extraction. - May be a custom model provided by Watson Knowledge Studio, or the default public - model `alchemy`. + :param str model: (optional) The enrichement model to use with entity + extraction. May be a custom model provided by Watson Knowledge Studio, or the + default public model `alchemy`. """ - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None, - mentions: bool = None, - mention_types: bool = None, - sentence_locations: bool = None, - model: str = None) -> None: + def __init__( + self, + *, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + limit: Optional[int] = None, + mentions: Optional[bool] = None, + mention_types: Optional[bool] = None, + sentence_locations: Optional[bool] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a NluEnrichmentEntities object. @@ -9089,20 +9660,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'mention_types' in _dict: - args['mention_types'] = _dict.get('mention_types') - if 'sentence_locations' in _dict: - args['sentence_locations'] = _dict.get('sentence_locations') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = mentions + if (mention_types := _dict.get('mention_types')) is not None: + args['mention_types'] = mention_types + if (sentence_locations := _dict.get('sentence_locations')) is not None: + args['sentence_locations'] = sentence_locations + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -9150,38 +9721,40 @@ def __ne__(self, other: 'NluEnrichmentEntities') -> bool: return not self == other -class NluEnrichmentFeatures(): +class NluEnrichmentFeatures: """ Object containing Natural Language Understanding features to be used. - :attr NluEnrichmentKeywords keywords: (optional) An object specifying the + :param NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword enrichment and related parameters. - :attr NluEnrichmentEntities entities: (optional) An object speficying the + :param NluEnrichmentEntities entities: (optional) An object speficying the Entities enrichment and related parameters. - :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the + :param NluEnrichmentSentiment sentiment: (optional) An object specifying the sentiment extraction enrichment and related parameters. - :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion + :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. - :attr dict categories: (optional) An object that indicates the Categories + :param dict categories: (optional) An object that indicates the Categories enrichment will be applied to the specified field. - :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object + :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. - :attr NluEnrichmentRelations relations: (optional) An object specifying the + :param NluEnrichmentRelations relations: (optional) An object specifying the relations enrichment and related parameters. - :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the + :param NluEnrichmentConcepts concepts: (optional) An object specifiying the concepts enrichment and related parameters. """ - def __init__(self, - *, - keywords: 'NluEnrichmentKeywords' = None, - entities: 'NluEnrichmentEntities' = None, - sentiment: 'NluEnrichmentSentiment' = None, - emotion: 'NluEnrichmentEmotion' = None, - categories: dict = None, - semantic_roles: 'NluEnrichmentSemanticRoles' = None, - relations: 'NluEnrichmentRelations' = None, - concepts: 'NluEnrichmentConcepts' = None) -> None: + def __init__( + self, + *, + keywords: Optional['NluEnrichmentKeywords'] = None, + entities: Optional['NluEnrichmentEntities'] = None, + sentiment: Optional['NluEnrichmentSentiment'] = None, + emotion: Optional['NluEnrichmentEmotion'] = None, + categories: Optional[dict] = None, + semantic_roles: Optional['NluEnrichmentSemanticRoles'] = None, + relations: Optional['NluEnrichmentRelations'] = None, + concepts: Optional['NluEnrichmentConcepts'] = None, + ) -> None: """ Initialize a NluEnrichmentFeatures object. @@ -9215,29 +9788,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} - if 'keywords' in _dict: - args['keywords'] = NluEnrichmentKeywords.from_dict( - _dict.get('keywords')) - if 'entities' in _dict: - args['entities'] = NluEnrichmentEntities.from_dict( - _dict.get('entities')) - if 'sentiment' in _dict: - args['sentiment'] = NluEnrichmentSentiment.from_dict( - _dict.get('sentiment')) - if 'emotion' in _dict: - args['emotion'] = NluEnrichmentEmotion.from_dict( - _dict.get('emotion')) - if 'categories' in _dict: - args['categories'] = _dict.get('categories') - if 'semantic_roles' in _dict: + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = NluEnrichmentKeywords.from_dict(keywords) + if (entities := _dict.get('entities')) is not None: + args['entities'] = NluEnrichmentEntities.from_dict(entities) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = NluEnrichmentSentiment.from_dict(sentiment) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = NluEnrichmentEmotion.from_dict(emotion) + if (categories := _dict.get('categories')) is not None: + args['categories'] = categories + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( - _dict.get('semantic_roles')) - if 'relations' in _dict: - args['relations'] = NluEnrichmentRelations.from_dict( - _dict.get('relations')) - if 'concepts' in _dict: - args['concepts'] = NluEnrichmentConcepts.from_dict( - _dict.get('concepts')) + semantic_roles) + if (relations := _dict.get('relations')) is not None: + args['relations'] = NluEnrichmentRelations.from_dict(relations) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = NluEnrichmentConcepts.from_dict(concepts) return cls(**args) @classmethod @@ -9306,23 +9873,25 @@ def __ne__(self, other: 'NluEnrichmentFeatures') -> bool: return not self == other -class NluEnrichmentKeywords(): +class NluEnrichmentKeywords: """ An object specifying the Keyword enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords + :param bool sentiment: (optional) When `true`, sentiment analysis of keywords will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of keywords will + :param bool emotion: (optional) When `true`, emotion detection of keywords will be performed on the specified field. - :attr int limit: (optional) The maximum number of keywords to extract for each + :param int limit: (optional) The maximum number of keywords to extract for each instance of the specified field. """ - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None) -> None: + def __init__( + self, + *, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentKeywords object. @@ -9341,12 +9910,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -9384,17 +9953,21 @@ def __ne__(self, other: 'NluEnrichmentKeywords') -> bool: return not self == other -class NluEnrichmentRelations(): +class NluEnrichmentRelations: """ An object specifying the relations enrichment and related parameters. - :attr str model: (optional) *For use with `natural_language_understanding` + :param str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the default public model is`en-news`. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a NluEnrichmentRelations object. @@ -9409,8 +9982,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -9444,23 +10017,25 @@ def __ne__(self, other: 'NluEnrichmentRelations') -> bool: return not self == other -class NluEnrichmentSemanticRoles(): +class NluEnrichmentSemanticRoles: """ An object specifiying the semantic roles enrichment and related parameters. - :attr bool entities: (optional) When `true`, entities are extracted from the + :param bool entities: (optional) When `true`, entities are extracted from the identified sentence parts. - :attr bool keywords: (optional) When `true`, keywords are extracted from the + :param bool keywords: (optional) When `true`, keywords are extracted from the identified sentence parts. - :attr int limit: (optional) The maximum number of semantic roles enrichments to + :param int limit: (optional) The maximum number of semantic roles enrichments to extact from each instance of the specified field. """ - def __init__(self, - *, - entities: bool = None, - keywords: bool = None, - limit: int = None) -> None: + def __init__( + self, + *, + entities: Optional[bool] = None, + keywords: Optional[bool] = None, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentSemanticRoles object. @@ -9479,12 +10054,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = _dict.get('entities') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (entities := _dict.get('entities')) is not None: + args['entities'] = entities + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = keywords + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -9522,20 +10097,22 @@ def __ne__(self, other: 'NluEnrichmentSemanticRoles') -> bool: return not self == other -class NluEnrichmentSentiment(): +class NluEnrichmentSentiment: """ An object specifying the sentiment extraction enrichment and related parameters. - :attr bool document: (optional) When `true`, sentiment analysis is performed on + :param bool document: (optional) When `true`, sentiment analysis is performed on the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a NluEnrichmentSentiment object. @@ -9551,10 +10128,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -9590,11 +10167,11 @@ def __ne__(self, other: 'NluEnrichmentSentiment') -> bool: return not self == other -class NormalizationOperation(): +class NormalizationOperation: """ Object containing normalization operations. - :attr str operation: (optional) Identifies what type of operation to perform. + :param str operation: (optional) Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** field. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. @@ -9619,15 +10196,18 @@ class NormalizationOperation(): this operation because _remove_nulls_ operates on the entire ingested document. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). - :attr str source_field: (optional) The source field for the operation. - :attr str destination_field: (optional) The destination field for the operation. + :param str source_field: (optional) The source field for the operation. + :param str destination_field: (optional) The destination field for the + operation. """ - def __init__(self, - *, - operation: str = None, - source_field: str = None, - destination_field: str = None) -> None: + def __init__( + self, + *, + operation: Optional[str] = None, + source_field: Optional[str] = None, + destination_field: Optional[str] = None, + ) -> None: """ Initialize a NormalizationOperation object. @@ -9670,12 +10250,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': """Initialize a NormalizationOperation object from a json dictionary.""" args = {} - if 'operation' in _dict: - args['operation'] = _dict.get('operation') - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') + if (operation := _dict.get('operation')) is not None: + args['operation'] = operation + if (source_field := _dict.get('source_field')) is not None: + args['source_field'] = source_field + if (destination_field := _dict.get('destination_field')) is not None: + args['destination_field'] = destination_field return cls(**args) @classmethod @@ -9740,6 +10320,7 @@ class OperationEnum(str, Enum): **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). """ + COPY = 'copy' MOVE = 'move' MERGE = 'merge' @@ -9747,11 +10328,11 @@ class OperationEnum(str, Enum): REMOVE_NULLS = 'remove_nulls' -class Notice(): +class Notice: """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have + :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs include: `index_failed`, `index_failed_too_many_requests`, @@ -9765,28 +10346,30 @@ class Notice(): `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete list; other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice + :param str document_id: (optional) Unique identifier of the document. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice occurred. Typical step values include: `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other values might be returned. - :attr str description: (optional) The description of the notice. + :param str description: (optional) The description of the notice. """ - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: + def __init__( + self, + *, + notice_id: Optional[str] = None, + created: Optional[datetime] = None, + document_id: Optional[str] = None, + query_id: Optional[str] = None, + severity: Optional[str] = None, + step: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -9803,20 +10386,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (notice_id := _dict.get('notice_id')) is not None: + args['notice_id'] = notice_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (severity := _dict.get('severity')) is not None: + args['severity'] = severity + if (step := _dict.get('step')) is not None: + args['step'] = step + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -9868,18 +10451,24 @@ class SeverityEnum(str, Enum): """ Severity level of the notice. """ + WARNING = 'warning' ERROR = 'error' -class PdfHeadingDetection(): +class PdfHeadingDetection: """ Object containing heading detection conversion settings for PDF documents. - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. + :param List[FontSetting] fonts: (optional) Array of font matching + configurations. """ - def __init__(self, *, fonts: List['FontSetting'] = None) -> None: + def __init__( + self, + *, + fonts: Optional[List['FontSetting']] = None, + ) -> None: """ Initialize a PdfHeadingDetection object. @@ -9892,10 +10481,8 @@ def __init__(self, *, fonts: List['FontSetting'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(v) for v in _dict.get('fonts') - ] + if (fonts := _dict.get('fonts')) is not None: + args['fonts'] = [FontSetting.from_dict(v) for v in fonts] return cls(**args) @classmethod @@ -9935,15 +10522,19 @@ def __ne__(self, other: 'PdfHeadingDetection') -> bool: return not self == other -class PdfSettings(): +class PdfSettings: """ A list of PDF conversion settings. - :attr PdfHeadingDetection heading: (optional) Object containing heading + :param PdfHeadingDetection heading: (optional) Object containing heading detection conversion settings for PDF documents. """ - def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: + def __init__( + self, + *, + heading: Optional['PdfHeadingDetection'] = None, + ) -> None: """ Initialize a PdfSettings object. @@ -9956,9 +10547,8 @@ def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfSettings': """Initialize a PdfSettings object from a json dictionary.""" args = {} - if 'heading' in _dict: - args['heading'] = PdfHeadingDetection.from_dict( - _dict.get('heading')) + if (heading := _dict.get('heading')) is not None: + args['heading'] = PdfHeadingDetection.from_dict(heading) return cls(**args) @classmethod @@ -9995,15 +10585,18 @@ def __ne__(self, other: 'PdfSettings') -> bool: return not self == other -class QueryAggregation(): +class QueryAggregation: """ An aggregation produced by Discovery to analyze the input provided. - :attr str type: The type of aggregation command used. For example: term, filter, - max, min, etc. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. """ - def __init__(self, type: str) -> None: + def __init__( + self, + type: str, + ) -> None: """ Initialize a QueryAggregation object. @@ -10019,8 +10612,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': if disc_class != cls: return disc_class.from_dict(_dict) args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryAggregation JSON' @@ -10086,22 +10679,24 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class QueryHistogramAggregationResult(): +class QueryHistogramAggregationResult: """ Histogram numeric interval result. - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: int, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryHistogramAggregationResult object. @@ -10119,21 +10714,21 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -10179,28 +10774,30 @@ def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: return not self == other -class QueryNoticesResponse(): +class QueryNoticesResponse: """ Object containing notice query results. - :attr int matching_results: (optional) The number of matching results. - :attr List[QueryNoticesResult] results: (optional) Array of document results + :param int matching_results: (optional) The number of matching results. + :param List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :attr List[QueryPassages] passages: (optional) Array of passage results that + :param List[QueryPassages] passages: (optional) Array of passage results that match the query. - :attr int duplicates_removed: (optional) The number of duplicates removed from + :param int duplicates_removed: (optional) The number of duplicates removed from this notices query. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryNoticesResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryNoticesResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + passages: Optional[List['QueryPassages']] = None, + duplicates_removed: Optional[int] = None, + ) -> None: """ Initialize a QueryNoticesResponse object. @@ -10224,22 +10821,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryNoticesResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryNoticesResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(v) for v in _dict.get('passages') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') + if (passages := _dict.get('passages')) is not None: + args['passages'] = [QueryPassages.from_dict(v) for v in passages] + if (duplicates_removed := _dict.get('duplicates_removed')) is not None: + args['duplicates_removed'] = duplicates_removed return cls(**args) @classmethod @@ -10302,23 +10895,23 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other -class QueryNoticesResult(): +class QueryNoticesResult: """ Query result object. - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection + :param str id: (optional) The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param str collection_id: (optional) The collection ID of the collection containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :attr int code: (optional) The internal status code returned by the ingestion + :param int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices for the document. + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file. + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). + :param List[Notice] notices: (optional) Array of notices for the document. """ # The set of defined properties for the class @@ -10327,18 +10920,20 @@ class QueryNoticesResult(): 'filename', 'file_type', 'sha1', 'notices' ]) - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - code: int = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None, - **kwargs) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + metadata: Optional[dict] = None, + collection_id: Optional[str] = None, + result_metadata: Optional['QueryResultMetadata'] = None, + code: Optional[int] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha1: Optional[str] = None, + notices: Optional[List['Notice']] = None, + **kwargs, + ) -> None: """ Initialize a QueryNoticesResult object. @@ -10375,27 +10970,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: + if (id := _dict.get('id')) is not None: + args['id'] = id + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) - if 'code' in _dict: - args['code'] = _dict.get('code') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + result_metadata) + if (code := _dict.get('code')) is not None: + args['code'] = code + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha1 := _dict.get('sha1')) is not None: + args['sha1'] = sha1 + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10488,37 +11081,40 @@ class FileTypeEnum(str, Enum): """ The type of the original source file. """ + PDF = 'pdf' HTML = 'html' WORD = 'word' JSON = 'json' -class QueryPassages(): +class QueryPassages: """ A passage query result. - :attr str document_id: (optional) The unique identifier of the document from + :param str document_id: (optional) The unique identifier of the document from which the passage has been extracted. - :attr float passage_score: (optional) The confidence score of the passages's + :param float passage_score: (optional) The confidence score of the passages's analysis. A higher score indicates greater confidence. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the + :param int end_offset: (optional) The position of the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. """ - def __init__(self, - *, - document_id: str = None, - passage_score: float = None, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + passage_score: Optional[float] = None, + passage_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + ) -> None: """ Initialize a QueryPassages object. @@ -10545,18 +11141,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryPassages': """Initialize a QueryPassages object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (passage_score := _dict.get('passage_score')) is not None: + args['passage_score'] = passage_score + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -10600,40 +11196,42 @@ def __ne__(self, other: 'QueryPassages') -> bool: return not self == other -class QueryResponse(): +class QueryResponse: """ A response containing the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the query. - :attr List[QueryResult] results: (optional) Array of document results for the + :param List[QueryResult] results: (optional) Array of document results for the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :attr List[QueryPassages] passages: (optional) Array of passage results for the + :param List[QueryPassages] passages: (optional) Array of passage results for the query. - :attr int duplicates_removed: (optional) The number of duplicate results + :param int duplicates_removed: (optional) The number of duplicate results removed. - :attr str session_token: (optional) The session token for this query. The + :param str session_token: (optional) The session token for this query. The session token can be used to add events associated with this query to the query and event log. **Important:** Session tokens are case sensitive. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) The suggestions for a misspelled natural + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) The suggestions for a misspelled natural language query. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None, - session_token: str = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + passages: Optional[List['QueryPassages']] = None, + duplicates_removed: Optional[int] = None, + session_token: Optional[str] = None, + retrieval_details: Optional['RetrievalDetails'] = None, + suggested_query: Optional[str] = None, + ) -> None: """ Initialize a QueryResponse object. @@ -10669,29 +11267,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(v) for v in _dict.get('passages') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'retrieval_details' in _dict: + if (passages := _dict.get('passages')) is not None: + args['passages'] = [QueryPassages.from_dict(v) for v in passages] + if (duplicates_removed := _dict.get('duplicates_removed')) is not None: + args['duplicates_removed'] = duplicates_removed + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token + if (retrieval_details := _dict.get('retrieval_details')) is not None: args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') + retrieval_details) + if (suggested_query := _dict.get('suggested_query')) is not None: + args['suggested_query'] = suggested_query return cls(**args) @classmethod @@ -10765,15 +11359,15 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other -class QueryResult(): +class QueryResult: """ Query result object. - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection + :param str id: (optional) The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param str collection_id: (optional) The collection ID of the collection containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. """ @@ -10781,13 +11375,15 @@ class QueryResult(): _properties = frozenset( ['id', 'metadata', 'collection_id', 'result_metadata']) - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - **kwargs) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + metadata: Optional[dict] = None, + collection_id: Optional[str] = None, + result_metadata: Optional['QueryResultMetadata'] = None, + **kwargs, + ) -> None: """ Initialize a QueryResult object. @@ -10810,15 +11406,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: + if (id := _dict.get('id')) is not None: + args['id'] = id + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10889,21 +11485,26 @@ def __ne__(self, other: 'QueryResult') -> bool: return not self == other -class QueryResultMetadata(): +class QueryResultMetadata: """ Metadata of a query result. - :attr float score: An unbounded measure of the relevance of a particular result, - dependent on the query and matching document. A higher score indicates a greater - match to the query parameters. - :attr float confidence: (optional) The confidence score for the given result. + :param float score: An unbounded measure of the relevance of a particular + result, dependent on the query and matching document. A higher score indicates a + greater match to the query parameters. + :param float confidence: (optional) The confidence score for the given result. Calculated based on how relevant the result is estimated to be. confidence can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. """ - def __init__(self, score: float, *, confidence: float = None) -> None: + def __init__( + self, + score: float, + *, + confidence: Optional[float] = None, + ) -> None: """ Initialize a QueryResultMetadata object. @@ -10924,14 +11525,14 @@ def __init__(self, score: float, *, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') + if (score := _dict.get('score')) is not None: + args['score'] = score else: raise ValueError( 'Required property \'score\' not present in QueryResultMetadata JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -10967,31 +11568,34 @@ def __ne__(self, other: 'QueryResultMetadata') -> bool: return not self == other -class QueryTermAggregationResult(): +class QueryTermAggregationResult: """ Top value result for the term aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which + :param str key: Value of the field with a non-zero frequency in the document + set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy for this term. + :param int total_matching_documents: (optional) The number of documents which have the term as the value of specified field in the whole set of documents in this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of + :param int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_documents: Optional[int] = None, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryTermAggregationResult object. @@ -11020,29 +11624,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTermAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') - if 'aggregations' in _dict: + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_documents := + _dict.get('estimated_matching_documents')) is not None: + args['estimated_matching_documents'] = estimated_matching_documents + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -11097,26 +11701,28 @@ def __ne__(self, other: 'QueryTermAggregationResult') -> bool: return not self == other -class QueryTimesliceAggregationResult(): +class QueryTimesliceAggregationResult: """ A timeslice interval segment. - :attr str key_as_string: String date value of the upper bound for the timeslice + :param str key_as_string: String date value of the upper bound for the timeslice interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval + :param int key: Numeric date value of the upper bound for the timeslice interval in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -11138,27 +11744,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = key_as_string else: raise ValueError( 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' ) - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -11206,18 +11812,20 @@ def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: return not self == other -class QueryTopHitsAggregationResult(): +class QueryTopHitsAggregationResult: """ A query response that contains the matching documents for the preceding aggregations. - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results. """ - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: + def __init__( + self, + matching_results: int, + *, + hits: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopHitsAggregationResult object. @@ -11231,14 +11839,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') + if (hits := _dict.get('hits')) is not None: + args['hits'] = hits return cls(**args) @classmethod @@ -11275,11 +11883,11 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other -class RetrievalDetails(): +class RetrievalDetails: """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Indentifies the document + :param str document_retrieval_strategy: (optional) Indentifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. `continuous_relevancy_training` indicates that the results were returned using @@ -11290,7 +11898,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__( + self, + *, + document_retrieval_strategy: Optional[str] = None, + ) -> None: """ Initialize a RetrievalDetails object. @@ -11311,9 +11923,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if (document_retrieval_strategy := + _dict.get('document_retrieval_strategy')) is not None: + args['document_retrieval_strategy'] = document_retrieval_strategy return cls(**args) @classmethod @@ -11360,45 +11972,48 @@ class DocumentRetrievalStrategyEnum(str, Enum): model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ + UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' -class SduStatus(): +class SduStatus: """ Object containing smart document understanding information for this collection. - :attr bool enabled: (optional) When `true`, smart document understanding + :param bool enabled: (optional) When `true`, smart document understanding conversion is enabled for this collection. All collections created with a version date after `2019-04-30` have smart document understanding enabled. If `false`, documents added to the collection are converted using the **conversion** settings specified in the configuration associated with the collection. - :attr int total_annotated_pages: (optional) The total number of pages annotated + :param int total_annotated_pages: (optional) The total number of pages annotated using smart document understanding in this collection. - :attr int total_pages: (optional) The current number of pages that can be used + :param int total_pages: (optional) The current number of pages that can be used for training smart document understanding. The `total_pages` number is calculated as the total number of pages identified from the documents listed in the **total_documents** field. - :attr int total_documents: (optional) The total number of documents in this + :param int total_documents: (optional) The total number of documents in this collection that can be used to train smart document understanding. For **lite** plan collections, the maximum is the first 20 uploaded documents (not including HTML or JSON documents). For other plans, the maximum is the first 40 uploaded documents (not including HTML or JSON documents). When the maximum is reached, additional documents uploaded to the collection are not considered for training smart document understanding. - :attr SduStatusCustomFields custom_fields: (optional) Information about custom + :param SduStatusCustomFields custom_fields: (optional) Information about custom smart document understanding fields that exist in this collection. """ - def __init__(self, - *, - enabled: bool = None, - total_annotated_pages: int = None, - total_pages: int = None, - total_documents: int = None, - custom_fields: 'SduStatusCustomFields' = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + total_annotated_pages: Optional[int] = None, + total_pages: Optional[int] = None, + total_documents: Optional[int] = None, + custom_fields: Optional['SduStatusCustomFields'] = None, + ) -> None: """ Initialize a SduStatus object. @@ -11434,17 +12049,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatus': """Initialize a SduStatus object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'total_annotated_pages' in _dict: - args['total_annotated_pages'] = _dict.get('total_annotated_pages') - if 'total_pages' in _dict: - args['total_pages'] = _dict.get('total_pages') - if 'total_documents' in _dict: - args['total_documents'] = _dict.get('total_documents') - if 'custom_fields' in _dict: + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (total_annotated_pages := + _dict.get('total_annotated_pages')) is not None: + args['total_annotated_pages'] = total_annotated_pages + if (total_pages := _dict.get('total_pages')) is not None: + args['total_pages'] = total_pages + if (total_documents := _dict.get('total_documents')) is not None: + args['total_documents'] = total_documents + if (custom_fields := _dict.get('custom_fields')) is not None: args['custom_fields'] = SduStatusCustomFields.from_dict( - _dict.get('custom_fields')) + custom_fields) return cls(**args) @classmethod @@ -11491,21 +12107,23 @@ def __ne__(self, other: 'SduStatus') -> bool: return not self == other -class SduStatusCustomFields(): +class SduStatusCustomFields: """ Information about custom smart document understanding fields that exist in this collection. - :attr int defined: (optional) The number of custom fields defined for this + :param int defined: (optional) The number of custom fields defined for this collection. - :attr int maximum_allowed: (optional) The maximum number of custom fields that + :param int maximum_allowed: (optional) The maximum number of custom fields that are allowed in this collection. """ - def __init__(self, - *, - defined: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + defined: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a SduStatusCustomFields object. @@ -11521,10 +12139,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} - if 'defined' in _dict: - args['defined'] = _dict.get('defined') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (defined := _dict.get('defined')) is not None: + args['defined'] = defined + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -11561,26 +12179,28 @@ def __ne__(self, other: 'SduStatusCustomFields') -> bool: return not self == other -class SearchStatus(): +class SearchStatus: """ Information about the Continuous Relevancy Training for this environment. - :attr str scope: (optional) Current scope of the training. Always returned as + :param str scope: (optional) Current scope of the training. Always returned as `environment`. - :attr str status: (optional) The current status of Continuous Relevancy Training - for this environment. - :attr str status_description: (optional) Long description of the current + :param str status: (optional) The current status of Continuous Relevancy + Training for this environment. + :param str status_description: (optional) Long description of the current Continuous Relevancy Training status. - :attr date last_trained: (optional) The date stamp of the most recent completed + :param date last_trained: (optional) The date stamp of the most recent completed training for this environment. """ - def __init__(self, - *, - scope: str = None, - status: str = None, - status_description: str = None, - last_trained: date = None) -> None: + def __init__( + self, + *, + scope: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + last_trained: Optional[date] = None, + ) -> None: """ Initialize a SearchStatus object. @@ -11602,14 +12222,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchStatus': """Initialize a SearchStatus object from a json dictionary.""" args = {} - if 'scope' in _dict: - args['scope'] = _dict.get('scope') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'last_trained' in _dict: - args['last_trained'] = string_to_date(_dict.get('last_trained')) + if (scope := _dict.get('scope')) is not None: + args['scope'] = scope + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_date(last_trained) return cls(**args) @classmethod @@ -11654,6 +12274,7 @@ class StatusEnum(str, Enum): """ The current status of Continuous Relevancy Training for this environment. """ + NO_DATA = 'NO_DATA' INSUFFICENT_DATA = 'INSUFFICENT_DATA' TRAINING = 'TRAINING' @@ -11661,34 +12282,36 @@ class StatusEnum(str, Enum): NOT_APPLICABLE = 'NOT_APPLICABLE' -class SegmentSettings(): +class SegmentSettings: """ A list of Document Segmentation settings. - :attr bool enabled: (optional) Enables/disables the Document Segmentation + :param bool enabled: (optional) Enables/disables the Document Segmentation feature. - :attr List[str] selector_tags: (optional) Defines the heading level that splits + :param List[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of the header field that the segmentation splits at is used as the **title** field for that segmented result. Only valid if used with a collection that has **enabled** set to `false` in the **smart_document_understanding** object. - :attr List[str] annotated_fields: (optional) Defines the annotated smart + :param List[str] annotated_fields: (optional) Defines the annotated smart document understanding fields that the document is split on. The content of the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, - when a document is uploaded each time the smart documement understanding + when a document is uploaded each time the smart document understanding conversion encounters a field of type `sub-title` the document is split at that point and the content of the field used as the title of the remaining content. - Thnis split is performed for all instances of the listed fields in the uploaded + This split is performed for all instances of the listed fields in the uploaded document. Only valid if used with a collection that has **enabled** set to `true` in the **smart_document_understanding** object. """ - def __init__(self, - *, - enabled: bool = None, - selector_tags: List[str] = None, - annotated_fields: List[str] = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + selector_tags: Optional[List[str]] = None, + annotated_fields: Optional[List[str]] = None, + ) -> None: """ Initialize a SegmentSettings object. @@ -11705,9 +12328,9 @@ def __init__(self, the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, when a document is uploaded each time the smart - documement understanding conversion encounters a field of type `sub-title` + document understanding conversion encounters a field of type `sub-title` the document is split at that point and the content of the field used as - the title of the remaining content. Thnis split is performed for all + the title of the remaining content. This split is performed for all instances of the listed fields in the uploaded document. Only valid if used with a collection that has **enabled** set to `true` in the **smart_document_understanding** object. @@ -11720,12 +12343,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SegmentSettings': """Initialize a SegmentSettings object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'selector_tags' in _dict: - args['selector_tags'] = _dict.get('selector_tags') - if 'annotated_fields' in _dict: - args['annotated_fields'] = _dict.get('annotated_fields') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (selector_tags := _dict.get('selector_tags')) is not None: + args['selector_tags'] = selector_tags + if (annotated_fields := _dict.get('annotated_fields')) is not None: + args['annotated_fields'] = annotated_fields return cls(**args) @classmethod @@ -11764,11 +12387,11 @@ def __ne__(self, other: 'SegmentSettings') -> bool: return not self == other -class Source(): +class Source: """ Object containing source parameters for the configuration. - :attr str type: (optional) The type of source to connect to. + :param str type: (optional) The type of source to connect to. - `box` indicates the configuration is to connect an instance of Enterprise Box. - `salesforce` indicates the configuration is to connect to Salesforce. @@ -11777,22 +12400,24 @@ class Source(): - `web_crawl` indicates the configuration is to perform a web page crawl. - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. - :attr str credential_id: (optional) The **credential_id** of the credentials to + :param str credential_id: (optional) The **credential_id** of the credentials to use to connect to the source. Credentials are defined using the **credentials** method. The **source_type** of the credentials used must match the **type** field specified in this object. - :attr SourceSchedule schedule: (optional) Object containing the schedule + :param SourceSchedule schedule: (optional) Object containing the schedule information for the source. - :attr SourceOptions options: (optional) The **options** object defines which + :param SourceOptions options: (optional) The **options** object defines which items to crawl from the source system. """ - def __init__(self, - *, - type: str = None, - credential_id: str = None, - schedule: 'SourceSchedule' = None, - options: 'SourceOptions' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + credential_id: Optional[str] = None, + schedule: Optional['SourceSchedule'] = None, + options: Optional['SourceOptions'] = None, + ) -> None: """ Initialize a Source object. @@ -11823,14 +12448,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Source': """Initialize a Source object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'schedule' in _dict: - args['schedule'] = SourceSchedule.from_dict(_dict.get('schedule')) - if 'options' in _dict: - args['options'] = SourceOptions.from_dict(_dict.get('options')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (schedule := _dict.get('schedule')) is not None: + args['schedule'] = SourceSchedule.from_dict(schedule) + if (options := _dict.get('options')) is not None: + args['options'] = SourceOptions.from_dict(options) return cls(**args) @classmethod @@ -11886,6 +12511,7 @@ class TypeEnum(str, Enum): - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. """ + BOX = 'box' SALESFORCE = 'salesforce' SHAREPOINT = 'sharepoint' @@ -11893,40 +12519,43 @@ class TypeEnum(str, Enum): CLOUD_OBJECT_STORAGE = 'cloud_object_storage' -class SourceOptions(): +class SourceOptions: """ The **options** object defines which items to crawl from the source system. - :attr List[SourceOptionsFolder] folders: (optional) Array of folders to crawl + :param List[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. - :attr List[SourceOptionsObject] objects: (optional) Array of Salesforce document - object types to crawl from the Salesforce source. Only valid, and required, when - the **type** field of the **source** object is set to `salesforce`. - :attr List[SourceOptionsSiteColl] site_collections: (optional) Array of + :param List[SourceOptionsObject] objects: (optional) Array of Salesforce + document object types to crawl from the Salesforce source. Only valid, and + required, when the **type** field of the **source** object is set to + `salesforce`. + :param List[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. - :attr List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to + :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. - :attr List[SourceOptionsBuckets] buckets: (optional) Array of cloud object store - buckets to begin crawling. Only valid and required when the **type** field of - the **source** object is set to `cloud_object_store`, and the + :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object + store buckets to begin crawling. Only valid and required when the **type** field + of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. - :attr bool crawl_all_buckets: (optional) When `true`, all buckets in the + :param bool crawl_all_buckets: (optional) When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array must not be specified. """ - def __init__(self, - *, - folders: List['SourceOptionsFolder'] = None, - objects: List['SourceOptionsObject'] = None, - site_collections: List['SourceOptionsSiteColl'] = None, - urls: List['SourceOptionsWebCrawl'] = None, - buckets: List['SourceOptionsBuckets'] = None, - crawl_all_buckets: bool = None) -> None: + def __init__( + self, + *, + folders: Optional[List['SourceOptionsFolder']] = None, + objects: Optional[List['SourceOptionsObject']] = None, + site_collections: Optional[List['SourceOptionsSiteColl']] = None, + urls: Optional[List['SourceOptionsWebCrawl']] = None, + buckets: Optional[List['SourceOptionsBuckets']] = None, + crawl_all_buckets: Optional[bool] = None, + ) -> None: """ Initialize a SourceOptions object. @@ -11963,29 +12592,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptions': """Initialize a SourceOptions object from a json dictionary.""" args = {} - if 'folders' in _dict: + if (folders := _dict.get('folders')) is not None: args['folders'] = [ - SourceOptionsFolder.from_dict(v) for v in _dict.get('folders') + SourceOptionsFolder.from_dict(v) for v in folders ] - if 'objects' in _dict: + if (objects := _dict.get('objects')) is not None: args['objects'] = [ - SourceOptionsObject.from_dict(v) for v in _dict.get('objects') + SourceOptionsObject.from_dict(v) for v in objects ] - if 'site_collections' in _dict: + if (site_collections := _dict.get('site_collections')) is not None: args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(v) - for v in _dict.get('site_collections') + SourceOptionsSiteColl.from_dict(v) for v in site_collections ] - if 'urls' in _dict: - args['urls'] = [ - SourceOptionsWebCrawl.from_dict(v) for v in _dict.get('urls') - ] - if 'buckets' in _dict: + if (urls := _dict.get('urls')) is not None: + args['urls'] = [SourceOptionsWebCrawl.from_dict(v) for v in urls] + if (buckets := _dict.get('buckets')) is not None: args['buckets'] = [ - SourceOptionsBuckets.from_dict(v) for v in _dict.get('buckets') + SourceOptionsBuckets.from_dict(v) for v in buckets ] - if 'crawl_all_buckets' in _dict: - args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') + if (crawl_all_buckets := _dict.get('crawl_all_buckets')) is not None: + args['crawl_all_buckets'] = crawl_all_buckets return cls(**args) @classmethod @@ -12061,16 +12687,21 @@ def __ne__(self, other: 'SourceOptions') -> bool: return not self == other -class SourceOptionsBuckets(): +class SourceOptionsBuckets: """ Object defining a cloud object store bucket to crawl. - :attr str name: The name of the cloud object store bucket to crawl. - :attr int limit: (optional) The number of documents to crawl from this cloud + :param str name: The name of the cloud object store bucket to crawl. + :param int limit: (optional) The number of documents to crawl from this cloud object store bucket. If not specified, all documents in the bucket are crawled. """ - def __init__(self, name: str, *, limit: int = None) -> None: + def __init__( + self, + name: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsBuckets object. @@ -12086,14 +12717,14 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SourceOptionsBuckets JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12129,22 +12760,24 @@ def __ne__(self, other: 'SourceOptionsBuckets') -> bool: return not self == other -class SourceOptionsFolder(): +class SourceOptionsFolder: """ Object that defines a box folder to crawl with this configuration. - :attr str owner_user_id: The Box user ID of the user who owns the folder to + :param str owner_user_id: The Box user ID of the user who owns the folder to crawl. - :attr str folder_id: The Box folder ID of the folder to crawl. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param str folder_id: The Box folder ID of the folder to crawl. + :param int limit: (optional) The maximum number of documents to crawl for this folder. By default, all documents in the folder are crawled. """ - def __init__(self, - owner_user_id: str, - folder_id: str, - *, - limit: int = None) -> None: + def __init__( + self, + owner_user_id: str, + folder_id: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsFolder object. @@ -12162,20 +12795,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} - if 'owner_user_id' in _dict: - args['owner_user_id'] = _dict.get('owner_user_id') + if (owner_user_id := _dict.get('owner_user_id')) is not None: + args['owner_user_id'] = owner_user_id else: raise ValueError( 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' ) - if 'folder_id' in _dict: - args['folder_id'] = _dict.get('folder_id') + if (folder_id := _dict.get('folder_id')) is not None: + args['folder_id'] = folder_id else: raise ValueError( 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12213,17 +12846,22 @@ def __ne__(self, other: 'SourceOptionsFolder') -> bool: return not self == other -class SourceOptionsObject(): +class SourceOptionsObject: """ Object that defines a Salesforce document object type crawl with this configuration. - :attr str name: The name of the Salesforce document object to crawl. For + :param str name: The name of the Salesforce document object to crawl. For example, `case`. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param int limit: (optional) The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. """ - def __init__(self, name: str, *, limit: int = None) -> None: + def __init__( + self, + name: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsObject object. @@ -12240,14 +12878,14 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SourceOptionsObject JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12283,19 +12921,24 @@ def __ne__(self, other: 'SourceOptionsObject') -> bool: return not self == other -class SourceOptionsSiteColl(): +class SourceOptionsSiteColl: """ Object that defines a Microsoft SharePoint site collection to crawl with this configuration. - :attr str site_collection_path: The Microsoft SharePoint Online site collection + :param str site_collection_path: The Microsoft SharePoint Online site collection path to crawl. The path must be be relative to the **organization_url** that was specified in the credentials associated with this source configuration. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param int limit: (optional) The maximum number of documents to crawl for this site collection. By default, all documents in the site collection are crawled. """ - def __init__(self, site_collection_path: str, *, limit: int = None) -> None: + def __init__( + self, + site_collection_path: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsSiteColl object. @@ -12314,14 +12957,15 @@ def __init__(self, site_collection_path: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} - if 'site_collection_path' in _dict: - args['site_collection_path'] = _dict.get('site_collection_path') + if (site_collection_path := + _dict.get('site_collection_path')) is not None: + args['site_collection_path'] = site_collection_path else: raise ValueError( 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12358,47 +13002,49 @@ def __ne__(self, other: 'SourceOptionsSiteColl') -> bool: return not self == other -class SourceOptionsWebCrawl(): +class SourceOptionsWebCrawl: """ Object defining which URL to crawl and how to crawl it. - :attr str url: The starting URL to crawl. - :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the + :param str url: The starting URL to crawl. + :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the specified URL are limited to the host part of the **url** field. - :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. + :param str crawl_speed: (optional) The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call. `normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive` means that up to ten URLs are fetched concurrently with a short delay between fetch calls. - :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl - to interact with HTTPS sites with SSL certificates with untrusted signers. - :attr int maximum_hops: (optional) The maximum number of hops to make from the + :param bool allow_untrusted_certificate: (optional) When `true`, allows the + crawl to interact with HTTPS sites with SSL certificates with untrusted signers. + :param int maximum_hops: (optional) The maximum number of hops to make from the initial URL. When a page is crawled each link on that page will also be crawled if it is within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, each link crawled from the first page is 1 hop, each link crawled from those pages is 2 hops, and so on. - :attr int request_timeout: (optional) The maximum milliseconds to wait for a + :param int request_timeout: (optional) The maximum milliseconds to wait for a response from the web server. - :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore + :param bool override_robots_txt: (optional) When `true`, the crawler will ignore any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. - :attr List[str] blacklist: (optional) Array of URL's to be excluded while + :param List[str] blacklist: (optional) Array of URL's to be excluded while crawling. The crawler will not follow links which contains this string. For example, listing `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`. """ - def __init__(self, - url: str, - *, - limit_to_starting_hosts: bool = None, - crawl_speed: str = None, - allow_untrusted_certificate: bool = None, - maximum_hops: int = None, - request_timeout: int = None, - override_robots_txt: bool = None, - blacklist: List[str] = None) -> None: + def __init__( + self, + url: str, + *, + limit_to_starting_hosts: Optional[bool] = None, + crawl_speed: Optional[str] = None, + allow_untrusted_certificate: Optional[bool] = None, + maximum_hops: Optional[int] = None, + request_timeout: Optional[int] = None, + override_robots_txt: Optional[bool] = None, + blacklist: Optional[List[str]] = None, + ) -> None: """ Initialize a SourceOptionsWebCrawl object. @@ -12442,28 +13088,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' ) - if 'limit_to_starting_hosts' in _dict: - args['limit_to_starting_hosts'] = _dict.get( - 'limit_to_starting_hosts') - if 'crawl_speed' in _dict: - args['crawl_speed'] = _dict.get('crawl_speed') - if 'allow_untrusted_certificate' in _dict: - args['allow_untrusted_certificate'] = _dict.get( - 'allow_untrusted_certificate') - if 'maximum_hops' in _dict: - args['maximum_hops'] = _dict.get('maximum_hops') - if 'request_timeout' in _dict: - args['request_timeout'] = _dict.get('request_timeout') - if 'override_robots_txt' in _dict: - args['override_robots_txt'] = _dict.get('override_robots_txt') - if 'blacklist' in _dict: - args['blacklist'] = _dict.get('blacklist') + if (limit_to_starting_hosts := + _dict.get('limit_to_starting_hosts')) is not None: + args['limit_to_starting_hosts'] = limit_to_starting_hosts + if (crawl_speed := _dict.get('crawl_speed')) is not None: + args['crawl_speed'] = crawl_speed + if (allow_untrusted_certificate := + _dict.get('allow_untrusted_certificate')) is not None: + args['allow_untrusted_certificate'] = allow_untrusted_certificate + if (maximum_hops := _dict.get('maximum_hops')) is not None: + args['maximum_hops'] = maximum_hops + if (request_timeout := _dict.get('request_timeout')) is not None: + args['request_timeout'] = request_timeout + if (override_robots_txt := + _dict.get('override_robots_txt')) is not None: + args['override_robots_txt'] = override_robots_txt + if (blacklist := _dict.get('blacklist')) is not None: + args['blacklist'] = blacklist return cls(**args) @classmethod @@ -12524,23 +13171,24 @@ class CrawlSpeedEnum(str, Enum): that up to ten URLs are fetched concurrently with a short delay between fetch calls. """ + GENTLE = 'gentle' NORMAL = 'normal' AGGRESSIVE = 'aggressive' -class SourceSchedule(): +class SourceSchedule: """ Object containing the schedule information for the source. - :attr bool enabled: (optional) When `true`, the source is re-crawled based on + :param bool enabled: (optional) When `true`, the source is re-crawled based on the **frequency** field in this object. When `false` the source is not re-crawled; When `false` and connecting to Salesforce the source is crawled annually. - :attr str time_zone: (optional) The time zone to base source crawl times on. + :param str time_zone: (optional) The time zone to base source crawl times on. Possible values correspond to the IANA (Internet Assigned Numbers Authority) time zones list. - :attr str frequency: (optional) The crawl schedule in the specified + :param str frequency: (optional) The crawl schedule in the specified **time_zone**. - `five_minutes`: Runs every five minutes. - `hourly`: Runs every hour. @@ -12550,11 +13198,13 @@ class SourceSchedule(): 06:00. """ - def __init__(self, - *, - enabled: bool = None, - time_zone: str = None, - frequency: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + time_zone: Optional[str] = None, + frequency: Optional[str] = None, + ) -> None: """ Initialize a SourceSchedule object. @@ -12582,12 +13232,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceSchedule': """Initialize a SourceSchedule object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'time_zone' in _dict: - args['time_zone'] = _dict.get('time_zone') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (time_zone := _dict.get('time_zone')) is not None: + args['time_zone'] = time_zone + if (frequency := _dict.get('frequency')) is not None: + args['frequency'] = frequency return cls(**args) @classmethod @@ -12633,6 +13283,7 @@ class FrequencyEnum(str, Enum): - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. """ + DAILY = 'daily' WEEKLY = 'weekly' MONTHLY = 'monthly' @@ -12640,11 +13291,11 @@ class FrequencyEnum(str, Enum): HOURLY = 'hourly' -class SourceStatus(): +class SourceStatus: """ Object containing source crawl status information. - :attr str status: (optional) The current status of the source crawl for this + :param str status: (optional) The current status of the source crawl for this collection. This field returns `not_configured` if the default configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. @@ -12652,14 +13303,16 @@ class SourceStatus(): - `queued` indicates that the crawl has been paused by the system and will automatically restart when possible. - `unknown` indicates that an unidentified error has occured in the service. - :attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the + :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating the time of the next crawl attempt. """ - def __init__(self, - *, - status: str = None, - next_crawl: datetime = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + next_crawl: Optional[datetime] = None, + ) -> None: """ Initialize a SourceStatus object. @@ -12682,10 +13335,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceStatus': """Initialize a SourceStatus object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'next_crawl' in _dict: - args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (next_crawl := _dict.get('next_crawl')) is not None: + args['next_crawl'] = string_to_datetime(next_crawl) return cls(**args) @classmethod @@ -12731,6 +13384,7 @@ class StatusEnum(str, Enum): automatically restart when possible. - `unknown` indicates that an unidentified error has occured in the service. """ + RUNNING = 'running' COMPLETE = 'complete' NOT_CONFIGURED = 'not_configured' @@ -12738,20 +13392,22 @@ class StatusEnum(str, Enum): UNKNOWN = 'unknown' -class StatusDetails(): +class StatusDetails: """ Object that contains details about the status of the authentication process. - :attr bool authenticated: (optional) Indicates whether the credential is + :param bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. - :attr str error_message: (optional) If `authenticated` is `false`, a message + :param str error_message: (optional) If `authenticated` is `false`, a message describes why authentication is unsuccessful. """ - def __init__(self, - *, - authenticated: bool = None, - error_message: str = None) -> None: + def __init__( + self, + *, + authenticated: Optional[bool] = None, + error_message: Optional[str] = None, + ) -> None: """ Initialize a StatusDetails object. @@ -12767,10 +13423,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'StatusDetails': """Initialize a StatusDetails object from a json dictionary.""" args = {} - if 'authenticated' in _dict: - args['authenticated'] = _dict.get('authenticated') - if 'error_message' in _dict: - args['error_message'] = _dict.get('error_message') + if (authenticated := _dict.get('authenticated')) is not None: + args['authenticated'] = authenticated + if (error_message := _dict.get('error_message')) is not None: + args['error_message'] = error_message return cls(**args) @classmethod @@ -12806,25 +13462,27 @@ def __ne__(self, other: 'StatusDetails') -> bool: return not self == other -class TokenDictRule(): +class TokenDictRule: """ An object defining a single tokenizaion rule. - :attr str text: The string to tokenize. - :attr List[str] tokens: Array of tokens that the `text` field is split into when - found. - :attr List[str] readings: (optional) Array of tokens that represent the content + :param str text: The string to tokenize. + :param List[str] tokens: Array of tokens that the `text` field is split into + when found. + :param List[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. - :attr str part_of_speech: The part of speech that the `text` string belongs to. + :param str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. """ - def __init__(self, - text: str, - tokens: List[str], - part_of_speech: str, - *, - readings: List[str] = None) -> None: + def __init__( + self, + text: str, + tokens: List[str], + part_of_speech: str, + *, + readings: Optional[List[str]] = None, + ) -> None: """ Initialize a TokenDictRule object. @@ -12845,21 +13503,21 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenDictRule': """Initialize a TokenDictRule object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in TokenDictRule JSON') - if 'tokens' in _dict: - args['tokens'] = _dict.get('tokens') + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = tokens else: raise ValueError( 'Required property \'tokens\' not present in TokenDictRule JSON' ) - if 'readings' in _dict: - args['readings'] = _dict.get('readings') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (readings := _dict.get('readings')) is not None: + args['readings'] = readings + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech else: raise ValueError( 'Required property \'part_of_speech\' not present in TokenDictRule JSON' @@ -12903,17 +13561,22 @@ def __ne__(self, other: 'TokenDictRule') -> bool: return not self == other -class TokenDictStatusResponse(): +class TokenDictStatusResponse: """ Object describing the current status of the wordlist. - :attr str status: (optional) Current wordlist status for the specified + :param str status: (optional) Current wordlist status for the specified collection. - :attr str type: (optional) The type for this wordlist. Can be + :param str type: (optional) The type for this wordlist. Can be `tokenization_dictionary` or `stopwords`. """ - def __init__(self, *, status: str = None, type: str = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a TokenDictStatusResponse object. @@ -12929,10 +13592,10 @@ def __init__(self, *, status: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (status := _dict.get('status')) is not None: + args['status'] = status + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -12971,29 +13634,32 @@ class StatusEnum(str, Enum): """ Current wordlist status for the specified collection. """ + ACTIVE = 'active' PENDING = 'pending' NOT_FOUND = 'not found' -class TrainingDataSet(): +class TrainingDataSet: """ Training information for a specific collection. - :attr str environment_id: (optional) The environment id associated with this + :param str environment_id: (optional) The environment id associated with this training data set. - :attr str collection_id: (optional) The collection id associated with this + :param str collection_id: (optional) The collection id associated with this training data set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. At + :param List[TrainingQuery] queries: (optional) Array of training queries. At least 50 queries are required for training to begin. A maximum of 10,000 queries are returned. """ - def __init__(self, - *, - environment_id: str = None, - collection_id: str = None, - queries: List['TrainingQuery'] = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + collection_id: Optional[str] = None, + queries: Optional[List['TrainingQuery']] = None, + ) -> None: """ Initialize a TrainingDataSet object. @@ -13013,14 +13679,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': """Initialize a TrainingDataSet object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(v) for v in _dict.get('queries') - ] + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (queries := _dict.get('queries')) is not None: + args['queries'] = [TrainingQuery.from_dict(v) for v in queries] return cls(**args) @classmethod @@ -13064,22 +13728,24 @@ def __ne__(self, other: 'TrainingDataSet') -> bool: return not self == other -class TrainingExample(): +class TrainingExample: """ Training example details. - :attr str document_id: (optional) The document ID associated with this training + :param str document_id: (optional) The document ID associated with this training example. - :attr str cross_reference: (optional) The cross reference associated with this + :param str cross_reference: (optional) The cross reference associated with this training example. - :attr int relevance: (optional) The relevance of the training example. + :param int relevance: (optional) The relevance of the training example. """ - def __init__(self, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + ) -> None: """ Initialize a TrainingExample object. @@ -13097,12 +13763,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'cross_reference' in _dict: - args['cross_reference'] = _dict.get('cross_reference') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (cross_reference := _dict.get('cross_reference')) is not None: + args['cross_reference'] = cross_reference + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance return cls(**args) @classmethod @@ -13141,14 +13807,18 @@ def __ne__(self, other: 'TrainingExample') -> bool: return not self == other -class TrainingExampleList(): +class TrainingExampleList: """ Object containing an array of training examples. - :attr List[TrainingExample] examples: (optional) Array of training examples. + :param List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, *, examples: List['TrainingExample'] = None) -> None: + def __init__( + self, + *, + examples: Optional[List['TrainingExample']] = None, + ) -> None: """ Initialize a TrainingExampleList object. @@ -13161,10 +13831,8 @@ def __init__(self, *, examples: List['TrainingExample'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': """Initialize a TrainingExampleList object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -13204,24 +13872,26 @@ def __ne__(self, other: 'TrainingExampleList') -> bool: return not self == other -class TrainingQuery(): +class TrainingQuery: """ Training query details. - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: (optional) The natural text query for the + :param str query_id: (optional) The query ID associated with the training query. + :param str natural_language_query: (optional) The natural text query for the training query. - :attr str filter: (optional) The filter used on the collection before the + :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr List[TrainingExample] examples: (optional) Array of training examples. + :param List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, - *, - query_id: str = None, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None) -> None: + def __init__( + self, + *, + query_id: Optional[str] = None, + natural_language_query: Optional[str] = None, + filter: Optional[str] = None, + examples: Optional[List['TrainingExample']] = None, + ) -> None: """ Initialize a TrainingQuery object. @@ -13243,16 +13913,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -13299,41 +13968,43 @@ def __ne__(self, other: 'TrainingQuery') -> bool: return not self == other -class TrainingStatus(): +class TrainingStatus: """ Training status details. - :attr int total_examples: (optional) The total number of training examples + :param int total_examples: (optional) The total number of training examples uploaded to this collection. - :attr bool available: (optional) When `true`, the collection has been + :param bool available: (optional) When `true`, the collection has been successfully trained. - :attr bool processing: (optional) When `true`, the collection is currently + :param bool processing: (optional) When `true`, the collection is currently processing training. - :attr bool minimum_queries_added: (optional) When `true`, the collection has a + :param bool minimum_queries_added: (optional) When `true`, the collection has a sufficent amount of queries added for training to occur. - :attr bool minimum_examples_added: (optional) When `true`, the collection has a + :param bool minimum_examples_added: (optional) When `true`, the collection has a sufficent amount of examples added for training to occur. - :attr bool sufficient_label_diversity: (optional) When `true`, the collection + :param bool sufficient_label_diversity: (optional) When `true`, the collection has a sufficent amount of diversity in labeled results for training to occur. - :attr int notices: (optional) The number of notices associated with this data + :param int notices: (optional) The number of notices associated with this data set. - :attr datetime successfully_trained: (optional) The timestamp of when the + :param datetime successfully_trained: (optional) The timestamp of when the collection was successfully trained. - :attr datetime data_updated: (optional) The timestamp of when the data was + :param datetime data_updated: (optional) The timestamp of when the data was uploaded. """ - def __init__(self, - *, - total_examples: int = None, - available: bool = None, - processing: bool = None, - minimum_queries_added: bool = None, - minimum_examples_added: bool = None, - sufficient_label_diversity: bool = None, - notices: int = None, - successfully_trained: datetime = None, - data_updated: datetime = None) -> None: + def __init__( + self, + *, + total_examples: Optional[int] = None, + available: Optional[bool] = None, + processing: Optional[bool] = None, + minimum_queries_added: Optional[bool] = None, + minimum_examples_added: Optional[bool] = None, + sufficient_label_diversity: Optional[bool] = None, + notices: Optional[int] = None, + successfully_trained: Optional[datetime] = None, + data_updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingStatus object. @@ -13371,26 +14042,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'successfully_trained' in _dict: + if (total_examples := _dict.get('total_examples')) is not None: + args['total_examples'] = total_examples + if (available := _dict.get('available')) is not None: + args['available'] = available + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (minimum_queries_added := + _dict.get('minimum_queries_added')) is not None: + args['minimum_queries_added'] = minimum_queries_added + if (minimum_examples_added := + _dict.get('minimum_examples_added')) is not None: + args['minimum_examples_added'] = minimum_examples_added + if (sufficient_label_diversity := + _dict.get('sufficient_label_diversity')) is not None: + args['sufficient_label_diversity'] = sufficient_label_diversity + if (notices := _dict.get('notices')) is not None: + args['notices'] = notices + if (successfully_trained := + _dict.get('successfully_trained')) is not None: args['successfully_trained'] = string_to_datetime( - _dict.get('successfully_trained')) - if 'data_updated' in _dict: - args['data_updated'] = string_to_datetime(_dict.get('data_updated')) + successfully_trained) + if (data_updated := _dict.get('data_updated')) is not None: + args['data_updated'] = string_to_datetime(data_updated) return cls(**args) @classmethod @@ -13446,19 +14120,22 @@ def __ne__(self, other: 'TrainingStatus') -> bool: return not self == other -class WordHeadingDetection(): +class WordHeadingDetection: """ Object containing heading detection conversion settings for Microsoft Word documents. - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. - :attr List[WordStyle] styles: (optional) Array of Microsoft Word styles to + :param List[FontSetting] fonts: (optional) Array of font matching + configurations. + :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ - def __init__(self, - *, - fonts: List['FontSetting'] = None, - styles: List['WordStyle'] = None) -> None: + def __init__( + self, + *, + fonts: Optional[List['FontSetting']] = None, + styles: Optional[List['WordStyle']] = None, + ) -> None: """ Initialize a WordHeadingDetection object. @@ -13474,14 +14151,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(v) for v in _dict.get('fonts') - ] - if 'styles' in _dict: - args['styles'] = [ - WordStyle.from_dict(v) for v in _dict.get('styles') - ] + if (fonts := _dict.get('fonts')) is not None: + args['fonts'] = [FontSetting.from_dict(v) for v in fonts] + if (styles := _dict.get('styles')) is not None: + args['styles'] = [WordStyle.from_dict(v) for v in styles] return cls(**args) @classmethod @@ -13529,15 +14202,19 @@ def __ne__(self, other: 'WordHeadingDetection') -> bool: return not self == other -class WordSettings(): +class WordSettings: """ A list of Word conversion settings. - :attr WordHeadingDetection heading: (optional) Object containing heading + :param WordHeadingDetection heading: (optional) Object containing heading detection conversion settings for Microsoft Word documents. """ - def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: + def __init__( + self, + *, + heading: Optional['WordHeadingDetection'] = None, + ) -> None: """ Initialize a WordSettings object. @@ -13550,9 +14227,8 @@ def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordSettings': """Initialize a WordSettings object from a json dictionary.""" args = {} - if 'heading' in _dict: - args['heading'] = WordHeadingDetection.from_dict( - _dict.get('heading')) + if (heading := _dict.get('heading')) is not None: + args['heading'] = WordHeadingDetection.from_dict(heading) return cls(**args) @classmethod @@ -13589,16 +14265,21 @@ def __ne__(self, other: 'WordSettings') -> bool: return not self == other -class WordStyle(): +class WordStyle: """ Microsoft Word styles to convert into a specified HTML head level. - :attr int level: (optional) HTML head level that content matching this style is + :param int level: (optional) HTML head level that content matching this style is tagged with. - :attr List[str] names: (optional) Array of word style names to convert. + :param List[str] names: (optional) Array of word style names to convert. """ - def __init__(self, *, level: int = None, names: List[str] = None) -> None: + def __init__( + self, + *, + level: Optional[int] = None, + names: Optional[List[str]] = None, + ) -> None: """ Initialize a WordStyle object. @@ -13613,10 +14294,10 @@ def __init__(self, *, level: int = None, names: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordStyle': """Initialize a WordStyle object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'names' in _dict: - args['names'] = _dict.get('names') + if (level := _dict.get('level')) is not None: + args['level'] = level + if (names := _dict.get('names')) is not None: + args['names'] = names return cls(**args) @classmethod @@ -13652,14 +14333,18 @@ def __ne__(self, other: 'WordStyle') -> bool: return not self == other -class XPathPatterns(): +class XPathPatterns: """ Object containing an array of XPaths. - :attr List[str] xpaths: (optional) An array to XPaths. + :param List[str] xpaths: (optional) An array to XPaths. """ - def __init__(self, *, xpaths: List[str] = None) -> None: + def __init__( + self, + *, + xpaths: Optional[List[str]] = None, + ) -> None: """ Initialize a XPathPatterns object. @@ -13671,8 +14356,8 @@ def __init__(self, *, xpaths: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'XPathPatterns': """Initialize a XPathPatterns object from a json dictionary.""" args = {} - if 'xpaths' in _dict: - args['xpaths'] = _dict.get('xpaths') + if (xpaths := _dict.get('xpaths')) is not None: + args['xpaths'] = xpaths return cls(**args) @classmethod @@ -13711,11 +14396,17 @@ class QueryCalculationAggregation(QueryAggregation): Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ - def __init__(self, type: str, field: str, *, value: float = None) -> None: + def __init__( + self, + type: str, + field: str, + *, + value: Optional[float] = None, + ) -> None: """ Initialize a QueryCalculationAggregation object. @@ -13732,20 +14423,20 @@ def __init__(self, type: str, field: str, *, value: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': """Initialize a QueryCalculationAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryCalculationAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryCalculationAggregation JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod @@ -13787,19 +14478,21 @@ class QueryFilterAggregation(QueryAggregation): """ A modifier that narrows the document set of the sub-aggregations it precedes. - :attr str match: The filter that is written in Discovery Query Language syntax + :param str match: The filter that is written in Discovery Query Language syntax and is applied to the documents before sub-aggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param int matching_results: Number of documents that match the filter. + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - type: str, - match: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + type: str, + match: str, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryFilterAggregation object. @@ -13820,27 +14513,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': """Initialize a QueryFilterAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryFilterAggregation JSON' ) - if 'match' in _dict: - args['match'] = _dict.get('match') + if (match := _dict.get('match')) is not None: + args['match'] = match else: raise ValueError( 'Required property \'match\' not present in QueryFilterAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -13893,22 +14586,23 @@ class QueryHistogramAggregation(QueryAggregation): Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split into. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: + self, + type: str, + field: str, + interval: int, + *, + name: Optional[str] = None, + results: Optional[List['QueryHistogramAggregationResult']] = None, + ) -> None: """ Initialize a QueryHistogramAggregation object. @@ -13932,30 +14626,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': """Initialize a QueryHistogramAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryHistogramAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryHistogramAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryHistogramAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14009,19 +14702,21 @@ class QueryNestedAggregation(QueryAggregation): A restriction that alters the document set that is used for sub-aggregations it precedes to nested documents found in the field specified. - :attr str path: The path to the document field to scope sub-aggregations to. - :attr int matching_results: Number of nested documents found in the specified + :param str path: The path to the document field to scope sub-aggregations to. + :param int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - type: str, - path: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + type: str, + path: str, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryNestedAggregation object. @@ -14043,27 +14738,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': """Initialize a QueryNestedAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryNestedAggregation JSON' ) - if 'path' in _dict: - args['path'] = _dict.get('path') + if (path := _dict.get('path')) is not None: + args['path'] = path else: raise ValueError( 'Required property \'path\' not present in QueryNestedAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -14115,21 +14810,23 @@ class QueryTermAggregation(QueryAggregation): """ Returns the top values for the field specified. - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. - :attr str name: (optional) Identifier specified in the query request of this + :param str field: The field in the document used to generate top values from. + :param int count: (optional) The number of top values returned. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values + :param List[QueryTermAggregationResult] results: (optional) Array of top values for the field. """ - def __init__(self, - type: str, - field: str, - *, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: + def __init__( + self, + type: str, + field: str, + *, + count: Optional[int] = None, + name: Optional[str] = None, + results: Optional[List['QueryTermAggregationResult']] = None, + ) -> None: """ Initialize a QueryTermAggregation object. @@ -14153,26 +14850,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': """Initialize a QueryTermAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTermAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryTermAggregation JSON' ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (count := _dict.get('count')) is not None: + args['count'] = count + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTermAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTermAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14225,23 +14921,24 @@ class QueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: + self, + type: str, + field: str, + interval: str, + *, + name: Optional[str] = None, + results: Optional[List['QueryTimesliceAggregationResult']] = None, + ) -> None: """ Initialize a QueryTimesliceAggregation object. @@ -14265,30 +14962,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': """Initialize a QueryTimesliceAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTimesliceAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryTimesliceAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14341,18 +15037,20 @@ class QueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) """ - def __init__(self, - type: str, - size: int, - *, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: + def __init__( + self, + type: str, + size: int, + *, + name: Optional[str] = None, + hits: Optional['QueryTopHitsAggregationResult'] = None, + ) -> None: """ Initialize a QueryTopHitsAggregation object. @@ -14372,23 +15070,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': """Initialize a QueryTopHitsAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTopHitsAggregation JSON' ) - if 'size' in _dict: - args['size'] = _dict.get('size') + if (size := _dict.get('size')) is not None: + args['size'] = size else: raise ValueError( 'Required property \'size\' not present in QueryTopHitsAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (hits := _dict.get('hits')) is not None: + args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) return cls(**args) @classmethod diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index d6af60eb..3bfead3d 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ IBM Watson® Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -61,7 +61,7 @@ def __init__( Construct a new client for the Discovery service. :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. + Specify dates in YYYY-MM-DD format. The current version is `2023-03-31`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -82,7 +82,10 @@ def __init__( # Projects ######################### - def list_projects(self, **kwargs) -> DetailedResponse: + def list_projects( + self, + **kwargs, + ) -> DetailedResponse: """ List projects. @@ -94,9 +97,11 @@ def list_projects(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_projects') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_projects', + ) headers.update(sdk_headers) params = { @@ -109,20 +114,24 @@ def list_projects(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v2/projects' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_project(self, - name: str, - type: str, - *, - default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> DetailedResponse: + def create_project( + self, + name: str, + type: str, + *, + default_query_parameters: Optional['DefaultQueryParams'] = None, + **kwargs, + ) -> DetailedResponse: """ Create a project. @@ -148,9 +157,11 @@ def create_project(self, if default_query_parameters is not None: default_query_parameters = convert_model(default_query_parameters) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_project', + ) headers.update(sdk_headers) params = { @@ -172,16 +183,22 @@ def create_project(self, headers['Accept'] = 'application/json' url = '/v2/projects' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_project(self, project_id: str, **kwargs) -> DetailedResponse: + def get_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Get project. @@ -197,9 +214,11 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_project', + ) headers.update(sdk_headers) params = { @@ -215,19 +234,23 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_project(self, - project_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def update_project( + self, + project_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a project. @@ -244,9 +267,11 @@ def update_project(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_project', + ) headers.update(sdk_headers) params = { @@ -269,16 +294,22 @@ def update_project(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: + def delete_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a project. @@ -296,9 +327,11 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_project', + ) headers.update(sdk_headers) params = { @@ -313,19 +346,23 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_fields(self, - project_id: str, - *, - collection_ids: List[str] = None, - **kwargs) -> DetailedResponse: + def list_fields( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ List fields. @@ -345,9 +382,11 @@ def list_fields(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_fields', + ) headers.update(sdk_headers) params = { @@ -364,10 +403,12 @@ def list_fields(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -376,7 +417,11 @@ def list_fields(self, # Collections ######################### - def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: + def list_collections( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List collections. @@ -392,9 +437,11 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_collections') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_collections', + ) headers.update(sdk_headers) params = { @@ -410,22 +457,26 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_collection(self, - project_id: str, - name: str, - *, - description: str = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def create_collection( + self, + project_id: str, + name: str, + *, + description: Optional[str] = None, + language: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ Create a collection. @@ -458,9 +509,11 @@ def create_collection(self, if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_collection', + ) headers.update(sdk_headers) params = { @@ -486,19 +539,25 @@ def create_collection(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - Get collection. + Get collection details. Get details about the specified collection. @@ -515,9 +574,11 @@ def get_collection(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_collection', + ) headers.update(sdk_headers) params = { @@ -534,26 +595,42 @@ def get_collection(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_collection(self, - project_id: str, - collection_id: str, - *, - name: str = None, - description: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def update_collection( + self, + project_id: str, + collection_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ Update a collection. - Updates the specified collection's name, description, and enrichments. + Updates the specified collection's name, description, enrichments, and + configuration. + If you apply normalization rules to data in an existing collection, you must + initiate reprocessing of the collection. To do so, from the *Manage fields* page + in the product user interface, temporarily change the data type of a field to + enable the reprocess button. Change the data type of the field back to its + original value, and then click **Apply changes and reprocess**. + To remove a configuration that applies JSON normalization operations as part of + the conversion phase of ingestion, specify an empty `json_normalizations` object + (`[]`) in the request. + To remove a configuration that applies JSON normalization operations after + enrichments are applied, specify an empty `normalizations` object (`[]`) in the + request. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -574,9 +651,11 @@ def update_collection(self, if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_collection', + ) headers.update(sdk_headers) params = { @@ -602,17 +681,23 @@ def update_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a collection. @@ -632,9 +717,11 @@ def delete_collection(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_collection', + ) headers.update(sdk_headers) params = { @@ -650,10 +737,12 @@ def delete_collection(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -662,25 +751,26 @@ def delete_collection(self, project_id: str, collection_id: str, # Documents ######################### - def list_documents(self, - project_id: str, - collection_id: str, - *, - count: int = None, - status: str = None, - has_notices: bool = None, - is_parent: bool = None, - parent_document_id: str = None, - sha256: str = None, - **kwargs) -> DetailedResponse: + def list_documents( + self, + project_id: str, + collection_id: str, + *, + count: Optional[int] = None, + status: Optional[str] = None, + has_notices: Optional[bool] = None, + is_parent: Optional[bool] = None, + parent_document_id: Optional[str] = None, + sha256: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List documents. Lists the documents in the specified collection. The list includes only the document ID of each document and returns information for up to 10,000 documents. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and - later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. It is not currently available from Premium plan instances. + later installed instances, and from IBM Cloud-managed instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -729,9 +819,11 @@ def list_documents(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_documents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_documents', + ) headers.update(sdk_headers) params = { @@ -754,24 +846,28 @@ def list_documents(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def add_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a document. @@ -800,12 +896,13 @@ def add_document(self, :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -834,9 +931,11 @@ def add_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='add_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='add_document', + ) headers.update(sdk_headers) params = { @@ -864,25 +963,31 @@ def add_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document(self, project_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def get_document( + self, + project_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document details. Get details about a specific document, whether the document is added by uploading a file or by crawling an external data source. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and - later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. It is not currently available from Premium plan instances. + later installed instances, and from IBM Cloud-managed instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -900,9 +1005,11 @@ def get_document(self, project_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document', + ) headers.update(sdk_headers) params = { @@ -920,25 +1027,29 @@ def get_document(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def update_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document. @@ -959,12 +1070,13 @@ def update_document(self, from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -995,9 +1107,11 @@ def update_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document', + ) headers.update(sdk_headers) params = { @@ -1026,22 +1140,26 @@ def update_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def delete_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Delete a document. @@ -1078,9 +1196,11 @@ def delete_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -1098,10 +1218,12 @@ def delete_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1110,25 +1232,28 @@ def delete_document(self, # Queries ######################### - def query(self, - project_id: str, - *, - collection_ids: List[str] = None, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - spelling_suggestions: bool = None, - table_results: 'QueryLargeTableResults' = None, - suggested_refinements: 'QueryLargeSuggestedRefinements' = None, - passages: 'QueryLargePassages' = None, - similar: 'QueryLargeSimilar' = None, - **kwargs) -> DetailedResponse: + def query( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + spelling_suggestions: Optional[bool] = None, + table_results: Optional['QueryLargeTableResults'] = None, + suggested_refinements: Optional[ + 'QueryLargeSuggestedRefinements'] = None, + passages: Optional['QueryLargePassages'] = None, + similar: Optional['QueryLargeSimilar'] = None, + **kwargs, + ) -> DetailedResponse: """ Query a project. @@ -1159,10 +1284,14 @@ def query(self, Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant documents listed first. Use a query search when you want to find the most - relevant search results. + relevant search results. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that returns relevant documents by using training data and natural language - understanding. + understanding. You can use this parameter or the **query** parameter to + specify the query input, but not both. To filter the results based on + criteria you specify, include the **filter** parameter in the request. :param str aggregation: (optional) An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For more information @@ -1220,9 +1349,11 @@ def query(self, if similar is not None: similar = convert_model(similar) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query', + ) headers.update(sdk_headers) params = { @@ -1259,27 +1390,34 @@ def query(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/query'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - project_id: str, - prefix: str, - *, - collection_ids: List[str] = None, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + def get_autocompletion( + self, + project_id: str, + prefix: str, + *, + collection_ids: Optional[List[str]] = None, + field: Optional[str] = None, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Get Autocomplete Suggestions. Returns completion query suggestions for the specified prefix. + Suggested words are based on terms from the project documents. Suggestions are not + based on terms from the project's search history, and the project does not learn + from previous user choices. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1302,9 +1440,11 @@ def get_autocompletion(self, if not prefix: raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_autocompletion') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_autocompletion', + ) headers.update(sdk_headers) params = { @@ -1325,24 +1465,28 @@ def get_autocompletion(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def query_collection_notices(self, - project_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def query_collection_notices( + self, + project_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Query collection notices. @@ -1362,10 +1506,14 @@ def query_collection_notices(self, :param str query: (optional) A query search that is written in the Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant - documents listed first. + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that - returns relevant documents by using training data and natural language - understanding. + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10,000**. @@ -1383,9 +1531,11 @@ def query_collection_notices(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_collection_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_collection_notices', + ) headers.update(sdk_headers) params = { @@ -1407,23 +1557,27 @@ def query_collection_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def query_notices(self, - project_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def query_notices( + self, + project_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Query project notices. @@ -1442,10 +1596,14 @@ def query_notices(self, :param str query: (optional) A query search that is written in the Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant - documents listed first. + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that - returns relevant documents by using training data and natural language - understanding. + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10,000**. @@ -1461,9 +1619,11 @@ def query_notices(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_notices', + ) headers.update(sdk_headers) params = { @@ -1484,10 +1644,12 @@ def query_notices(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1496,8 +1658,12 @@ def query_notices(self, # Query modifications ######################### - def get_stopword_list(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom stop words list. @@ -1518,9 +1684,11 @@ def get_stopword_list(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1537,20 +1705,24 @@ def get_stopword_list(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_stopword_list(self, - project_id: str, - collection_id: str, - *, - stopwords: List[str] = None, - **kwargs) -> DetailedResponse: + def create_stopword_list( + self, + project_id: str, + collection_id: str, + *, + stopwords: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom stop words list. @@ -1579,9 +1751,11 @@ def create_stopword_list(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1605,17 +1779,23 @@ def create_stopword_list(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_stopword_list(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom stop words list. @@ -1636,9 +1816,11 @@ def delete_stopword_list(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1654,16 +1836,22 @@ def delete_stopword_list(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_expansions(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get the expansion list. @@ -1683,9 +1871,11 @@ def list_expansions(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_expansions', + ) headers.update(sdk_headers) params = { @@ -1702,17 +1892,23 @@ def list_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_expansions(self, project_id: str, collection_id: str, - expansions: List['Expansion'], - **kwargs) -> DetailedResponse: + def create_expansions( + self, + project_id: str, + collection_id: str, + expansions: List['Expansion'], + **kwargs, + ) -> DetailedResponse: """ Create or update an expansion list. @@ -1751,9 +1947,11 @@ def create_expansions(self, project_id: str, collection_id: str, raise ValueError('expansions must be provided') expansions = [convert_model(x) for x in expansions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_expansions', + ) headers.update(sdk_headers) params = { @@ -1777,17 +1975,23 @@ def create_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_expansions(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete the expansion list. @@ -1807,9 +2011,11 @@ def delete_expansions(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_expansions', + ) headers.update(sdk_headers) params = { @@ -1825,10 +2031,12 @@ def delete_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1837,8 +2045,11 @@ def delete_expansions(self, project_id: str, collection_id: str, # Component settings ######################### - def get_component_settings(self, project_id: str, - **kwargs) -> DetailedResponse: + def get_component_settings( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List component settings. @@ -1854,9 +2065,11 @@ def get_component_settings(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_component_settings') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_component_settings', + ) headers.update(sdk_headers) params = { @@ -1873,10 +2086,12 @@ def get_component_settings(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/component_settings'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1885,8 +2100,11 @@ def get_component_settings(self, project_id: str, # Training data ######################### - def list_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def list_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List training queries. @@ -1902,9 +2120,11 @@ def list_training_queries(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_training_queries', + ) headers.update(sdk_headers) params = { @@ -1921,16 +2141,21 @@ def list_training_queries(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def delete_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete training queries. @@ -1946,9 +2171,11 @@ def delete_training_queries(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_queries', + ) headers.update(sdk_headers) params = { @@ -1964,26 +2191,31 @@ def delete_training_queries(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_training_query(self, - project_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def create_training_query( + self, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Create training query. + Create a training query. Add a query to the training data for this project. The query can contain a filter and natural language query. + **Note**: You cannot apply relevancy training to a `content_mining` project type. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1991,7 +2223,11 @@ def create_training_query(self, the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object @@ -2005,9 +2241,11 @@ def create_training_query(self, raise ValueError('examples must be provided') examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_training_query', + ) headers.update(sdk_headers) params = { @@ -2033,17 +2271,23 @@ def create_training_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def get_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a training data query. @@ -2063,9 +2307,11 @@ def get_training_query(self, project_id: str, query_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_training_query', + ) headers.update(sdk_headers) params = { @@ -2082,26 +2328,31 @@ def get_training_query(self, project_id: str, query_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_training_query(self, - project_id: str, - query_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def update_training_query( + self, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a training query. - Updates an existing training query and it's examples. + Updates an existing training query and its examples. You must resubmit all of the + examples with the update request. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2110,7 +2361,11 @@ def update_training_query(self, the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object @@ -2126,9 +2381,11 @@ def update_training_query(self, raise ValueError('examples must be provided') examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_training_query', + ) headers.update(sdk_headers) params = { @@ -2154,22 +2411,30 @@ def update_training_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def delete_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a training data query. Removes details from a training data query, including the query string and all examples. + To delete an example, use the *Update a training query* method and omit the + example that you want to delete from the example set. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2184,9 +2449,11 @@ def delete_training_query(self, project_id: str, query_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_query', + ) headers.update(sdk_headers) params = { @@ -2202,10 +2469,12 @@ def delete_training_query(self, project_id: str, query_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2214,7 +2483,11 @@ def delete_training_query(self, project_id: str, query_id: str, # Enrichments ######################### - def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: + def list_enrichments( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List enrichments. @@ -2232,9 +2505,11 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_enrichments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_enrichments', + ) headers.update(sdk_headers) params = { @@ -2250,20 +2525,24 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_enrichment(self, - project_id: str, - enrichment: 'CreateEnrichment', - *, - file: BinaryIO = None, - **kwargs) -> DetailedResponse: + def create_enrichment( + self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Create an enrichment. @@ -2277,7 +2556,8 @@ def create_enrichment(self, enrichment. :param BinaryIO file: (optional) The enrichment file to upload. Expected file types per enrichment are as follows: - * CSV for `dictionary` + * CSV for `dictionary` and `sentence_classifier` (the training data CSV + file to upload). * PEAR for `uima_annotator` and `rule_based` (Explorer) * ZIP for `watson_knowledge_studio_model` and `rule_based` (Studio Advanced Rule Editor). @@ -2291,9 +2571,11 @@ def create_enrichment(self, if enrichment is None: raise ValueError('enrichment must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment', + ) headers.update(sdk_headers) params = { @@ -2315,17 +2597,23 @@ def create_enrichment(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def get_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: """ Get enrichment. @@ -2344,9 +2632,11 @@ def get_enrichment(self, project_id: str, enrichment_id: str, if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment', + ) headers.update(sdk_headers) params = { @@ -2363,21 +2653,25 @@ def get_enrichment(self, project_id: str, enrichment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_enrichment(self, - project_id: str, - enrichment_id: str, - name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def update_enrichment( + self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update an enrichment. @@ -2400,9 +2694,11 @@ def update_enrichment(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment', + ) headers.update(sdk_headers) params = { @@ -2427,17 +2723,23 @@ def update_enrichment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def delete_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete an enrichment. @@ -2457,9 +2759,11 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment', + ) headers.update(sdk_headers) params = { @@ -2475,10 +2779,12 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2487,8 +2793,11 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, # Document classifiers ######################### - def list_document_classifiers(self, project_id: str, - **kwargs) -> DetailedResponse: + def list_document_classifiers( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List document classifiers. @@ -2505,9 +2814,11 @@ def list_document_classifiers(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_document_classifiers') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifiers', + ) headers.update(sdk_headers) params = { @@ -2524,21 +2835,25 @@ def list_document_classifiers(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_document_classifier(self, - project_id: str, - training_data: BinaryIO, - classifier: 'CreateDocumentClassifier', - *, - test_data: BinaryIO = None, - **kwargs) -> DetailedResponse: + def create_document_classifier( + self, + project_id: str, + training_data: BinaryIO, + classifier: 'CreateDocumentClassifier', + *, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Create a document classifier. @@ -2577,9 +2892,11 @@ def create_document_classifier(self, if classifier is None: raise ValueError('classifier must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2603,17 +2920,23 @@ def create_document_classifier(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_classifier(self, project_id: str, classifier_id: str, - **kwargs) -> DetailedResponse: + def get_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a document classifier. @@ -2632,9 +2955,11 @@ def get_document_classifier(self, project_id: str, classifier_id: str, if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2651,22 +2976,26 @@ def get_document_classifier(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document_classifier(self, - project_id: str, - classifier_id: str, - classifier: 'UpdateDocumentClassifier', - *, - training_data: BinaryIO = None, - test_data: BinaryIO = None, - **kwargs) -> DetailedResponse: + def update_document_classifier( + self, + project_id: str, + classifier_id: str, + classifier: 'UpdateDocumentClassifier', + *, + training_data: Optional[BinaryIO] = None, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document classifier. @@ -2702,9 +3031,11 @@ def update_document_classifier(self, if classifier is None: raise ValueError('classifier must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2730,17 +3061,23 @@ def update_document_classifier(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document_classifier(self, project_id: str, classifier_id: str, - **kwargs) -> DetailedResponse: + def delete_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document classifier. @@ -2759,9 +3096,11 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2777,10 +3116,12 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2789,9 +3130,12 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, # Document classifier models ######################### - def list_document_classifier_models(self, project_id: str, - classifier_id: str, - **kwargs) -> DetailedResponse: + def list_document_classifier_models( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ List document classifier models. @@ -2814,7 +3158,8 @@ def list_document_classifier_models(self, project_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_document_classifier_models') + operation_id='list_document_classifier_models', + ) headers.update(sdk_headers) params = { @@ -2831,27 +3176,30 @@ def list_document_classifier_models(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_document_classifier_model( - self, - project_id: str, - classifier_id: str, - name: str, - *, - description: str = None, - learning_rate: float = None, - l1_regularization_strengths: List[float] = None, - l2_regularization_strengths: List[float] = None, - training_max_steps: int = None, - improvement_ratio: float = None, - **kwargs) -> DetailedResponse: + self, + project_id: str, + classifier_id: str, + name: str, + *, + description: Optional[str] = None, + learning_rate: Optional[float] = None, + l1_regularization_strengths: Optional[List[float]] = None, + l2_regularization_strengths: Optional[List[float]] = None, + training_max_steps: Optional[int] = None, + improvement_ratio: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Create a document classifier model. @@ -2902,7 +3250,8 @@ def create_document_classifier_model( sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_document_classifier_model') + operation_id='create_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -2932,18 +3281,24 @@ def create_document_classifier_model( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_document_classifier_model(self, project_id: str, classifier_id: str, - model_id: str, - **kwargs) -> DetailedResponse: + def get_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a document classifier model. @@ -2968,7 +3323,8 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_document_classifier_model') + operation_id='get_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -2986,22 +3342,26 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document_classifier_model(self, - project_id: str, - classifier_id: str, - model_id: str, - *, - name: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def update_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document classifier model. @@ -3028,7 +3388,8 @@ def update_document_classifier_model(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_document_classifier_model') + operation_id='update_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -3054,18 +3415,24 @@ def update_document_classifier_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_document_classifier_model(self, project_id: str, - classifier_id: str, model_id: str, - **kwargs) -> DetailedResponse: + def delete_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document classifier model. @@ -3090,7 +3457,8 @@ def delete_document_classifier_model(self, project_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_document_classifier_model') + operation_id='delete_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -3107,10 +3475,12 @@ def delete_document_classifier_model(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3119,17 +3489,19 @@ def delete_document_classifier_model(self, project_id: str, # Analyze ######################### - def analyze_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def analyze_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Analyze a Document. + Analyze a document. Process a document and return it for realtime use. Supports JSON files only. The file is not stored in the collection, but is processed according to the @@ -3139,18 +3511,23 @@ def analyze_document(self, enrichments to the `Quote` field in the collection configuration. Then, when you analyze the file, the text in the `Quote` field is analyzed and results are written to a field named `enriched_Quote`. + Submit a request against only one collection at a time. Remember, the documents in + the collection are not significant. It is the enrichments that are defined for the + collection that matter. If you submit requests to several collections, then + several models are initiated at the same time, which can cause request failures. **Note:** This method is supported with Enterprise plan deployments and installed deployments only. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -3174,9 +3551,11 @@ def analyze_document(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='analyze_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='analyze_document', + ) headers.update(sdk_headers) params = { @@ -3204,11 +3583,13 @@ def analyze_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response @@ -3217,7 +3598,11 @@ def analyze_document(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3239,9 +3624,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3254,10 +3641,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3272,6 +3661,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3289,6 +3679,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3306,6 +3697,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3319,20 +3711,22 @@ class FileContentType(str, Enum): ############################################################################## -class AnalyzedDocument(): +class AnalyzedDocument: """ An object that contains the converted document and any identified enrichments. Root-level fields from the original file are returned also. - :attr List[Notice] notices: (optional) Array of notices that are triggered when + :param List[Notice] notices: (optional) Array of notices that are triggered when the files are processed. - :attr AnalyzedResult result: (optional) Result of the document analysis. + :param AnalyzedResult result: (optional) Result of the document analysis. """ - def __init__(self, - *, - notices: List['Notice'] = None, - result: 'AnalyzedResult' = None) -> None: + def __init__( + self, + *, + notices: Optional[List['Notice']] = None, + result: Optional['AnalyzedResult'] = None, + ) -> None: """ Initialize a AnalyzedDocument object. @@ -3347,12 +3741,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': """Initialize a AnalyzedDocument object from a json dictionary.""" args = {} - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'result' in _dict: - args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (result := _dict.get('result')) is not None: + args['result'] = AnalyzedResult.from_dict(result) return cls(**args) @classmethod @@ -3397,17 +3789,22 @@ def __ne__(self, other: 'AnalyzedDocument') -> bool: return not self == other -class AnalyzedResult(): +class AnalyzedResult: """ Result of the document analysis. - :attr dict metadata: (optional) Metadata that was specified with the request. + :param dict metadata: (optional) Metadata that was specified with the request. """ # The set of defined properties for the class _properties = frozenset(['metadata']) - def __init__(self, *, metadata: dict = None, **kwargs) -> None: + def __init__( + self, + *, + metadata: Optional[dict] = None, + **kwargs, + ) -> None: """ Initialize a AnalyzedResult object. @@ -3423,8 +3820,8 @@ def __init__(self, *, metadata: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': """Initialize a AnalyzedResult object from a json dictionary.""" args = {} - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -3488,16 +3885,19 @@ def __ne__(self, other: 'AnalyzedResult') -> bool: return not self == other -class ClassifierFederatedModel(): +class ClassifierFederatedModel: """ An object with details for creating federated document classifier models. - :attr str field: Name of the field that contains the values from which multiple + :param str field: Name of the field that contains the values from which multiple classifier models are defined. For example, you can specify a field that lists product lines to create a separate model per product line. """ - def __init__(self, field: str) -> None: + def __init__( + self, + field: str, + ) -> None: """ Initialize a ClassifierFederatedModel object. @@ -3511,8 +3911,8 @@ def __init__(self, field: str) -> None: def from_dict(cls, _dict: Dict) -> 'ClassifierFederatedModel': """Initialize a ClassifierFederatedModel object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in ClassifierFederatedModel JSON' @@ -3550,24 +3950,27 @@ def __ne__(self, other: 'ClassifierFederatedModel') -> bool: return not self == other -class ClassifierModelEvaluation(): +class ClassifierModelEvaluation: """ An object that contains information about a trained document classifier model. - :attr ModelEvaluationMicroAverage micro_average: A micro-average aggregates the + :param ModelEvaluationMicroAverage micro_average: A micro-average aggregates the contributions of all classes to compute the average metric. Classes refers to the classification labels that are specified in the **answer_field**. - :attr ModelEvaluationMacroAverage macro_average: A macro-average computes metric - independently for each class and then takes the average. Class refers to the - classification label that is specified in the **answer_field**. - :attr List[PerClassModelEvaluation] per_class: An array of evaluation metrics, + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class refers to + the classification label that is specified in the **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation metrics, one set of metrics for each class, where class refers to the classification label that is specified in the **answer_field**. """ - def __init__(self, micro_average: 'ModelEvaluationMicroAverage', - macro_average: 'ModelEvaluationMacroAverage', - per_class: List['PerClassModelEvaluation']) -> None: + def __init__( + self, + micro_average: 'ModelEvaluationMicroAverage', + macro_average: 'ModelEvaluationMacroAverage', + per_class: List['PerClassModelEvaluation'], + ) -> None: """ Initialize a ClassifierModelEvaluation object. @@ -3591,24 +3994,23 @@ def __init__(self, micro_average: 'ModelEvaluationMicroAverage', def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': """Initialize a ClassifierModelEvaluation object from a json dictionary.""" args = {} - if 'micro_average' in _dict: + if (micro_average := _dict.get('micro_average')) is not None: args['micro_average'] = ModelEvaluationMicroAverage.from_dict( - _dict.get('micro_average')) + micro_average) else: raise ValueError( 'Required property \'micro_average\' not present in ClassifierModelEvaluation JSON' ) - if 'macro_average' in _dict: + if (macro_average := _dict.get('macro_average')) is not None: args['macro_average'] = ModelEvaluationMacroAverage.from_dict( - _dict.get('macro_average')) + macro_average) else: raise ValueError( 'Required property \'macro_average\' not present in ClassifierModelEvaluation JSON' ) - if 'per_class' in _dict: + if (per_class := _dict.get('per_class')) is not None: args['per_class'] = [ - PerClassModelEvaluation.from_dict(v) - for v in _dict.get('per_class') + PerClassModelEvaluation.from_dict(v) for v in per_class ] else: raise ValueError( @@ -3663,15 +4065,20 @@ def __ne__(self, other: 'ClassifierModelEvaluation') -> bool: return not self == other -class Collection(): +class Collection: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: (optional) The name of the collection. """ - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def __init__( + self, + *, + collection_id: Optional[str] = None, + name: Optional[str] = None, + ) -> None: """ Initialize a Collection object. @@ -3684,10 +4091,10 @@ def __init__(self, *, collection_id: str = None, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -3724,25 +4131,26 @@ def __ne__(self, other: 'Collection') -> bool: return not self == other -class CollectionDetails(): +class CollectionDetails: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: The name of the collection. - :attr str description: (optional) A description of the collection. - :attr datetime created: (optional) The date that the collection was created. - :attr str language: (optional) The language of the collection. For a list of + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param datetime created: (optional) The date that the collection was created. + :param str language: (optional) The language of the collection. For a list of supported languages, see the [product documentation](/docs/discovery-data?topic=discovery-data-language-support). - :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments - that are applied to this collection. To get a list of enrichments that are - available for a project, use the [List enrichments](#listenrichments) method. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of enrichments + that are available for a project, use the [List enrichments](#listenrichments) + method. If no enrichments are specified when the collection is created, the default enrichments for the project type are applied. For more information about project default settings, see the [product documentation](/docs/discovery-data?topic=discovery-data-project-defaults). - :attr CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: + :param CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: (optional) An object that describes the Smart Document Understanding model for a collection. """ @@ -3751,13 +4159,13 @@ def __init__( self, name: str, *, - collection_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - smart_document_understanding: - 'CollectionDetailsSmartDocumentUnderstanding' = None + collection_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + smart_document_understanding: Optional[ + 'CollectionDetailsSmartDocumentUnderstanding'] = None, ) -> None: """ Initialize a CollectionDetails object. @@ -3788,29 +4196,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'CollectionDetails': """Initialize a CollectionDetails object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in CollectionDetails JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'enrichments' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - CollectionEnrichment.from_dict(v) - for v in _dict.get('enrichments') + CollectionEnrichment.from_dict(v) for v in enrichments ] - if 'smart_document_understanding' in _dict: + if (smart_document_understanding := + _dict.get('smart_document_understanding')) is not None: args[ 'smart_document_understanding'] = CollectionDetailsSmartDocumentUnderstanding.from_dict( - _dict.get('smart_document_understanding')) + smart_document_understanding) return cls(**args) @classmethod @@ -3869,13 +4277,13 @@ def __ne__(self, other: 'CollectionDetails') -> bool: return not self == other -class CollectionDetailsSmartDocumentUnderstanding(): +class CollectionDetailsSmartDocumentUnderstanding: """ An object that describes the Smart Document Understanding model for a collection. - :attr bool enabled: (optional) When `true`, smart document understanding + :param bool enabled: (optional) When `true`, smart document understanding conversion is enabled for the collection. - :attr str model: (optional) Specifies the type of Smart Document Understanding + :param str model: (optional) Specifies the type of Smart Document Understanding (SDU) model that is enabled for the collection. The following types of models are supported: * `custom`: A user-trained model is applied. @@ -3891,7 +4299,12 @@ class CollectionDetailsSmartDocumentUnderstanding(): documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). """ - def __init__(self, *, enabled: bool = None, model: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a CollectionDetailsSmartDocumentUnderstanding object. @@ -3920,10 +4333,10 @@ def from_dict(cls, _dict: Dict) -> 'CollectionDetailsSmartDocumentUnderstanding': """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -3974,29 +4387,32 @@ class ModelEnum(str, Enum): fields* page of the product user interface. For more information, see [the product documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). """ + CUSTOM = 'custom' PRE_TRAINED = 'pre_trained' TEXT_EXTRACTION = 'text_extraction' -class CollectionEnrichment(): +class CollectionEnrichment: """ An object describing an enrichment for a collection. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :param str enrichment_id: (optional) The unique identifier of this enrichment. For more information about how to determine the ID of an enrichment, see [the product documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). - :attr List[str] fields: (optional) An array of field names that the enrichment + :param List[str] fields: (optional) An array of field names that the enrichment is applied to. If you apply an enrichment to a field from a JSON file, the data is converted to an array automatically, even if the field contains a single value. """ - def __init__(self, - *, - enrichment_id: str = None, - fields: List[str] = None) -> None: + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + fields: Optional[List[str]] = None, + ) -> None: """ Initialize a CollectionEnrichment object. @@ -4017,10 +4433,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': """Initialize a CollectionEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields return cls(**args) @classmethod @@ -4056,15 +4472,19 @@ def __ne__(self, other: 'CollectionEnrichment') -> bool: return not self == other -class Completions(): +class Completions: """ An object that contains an array of autocompletion suggestions. - :attr List[str] completions: (optional) Array of autocomplete suggestion based + :param List[str] completions: (optional) Array of autocomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__( + self, + *, + completions: Optional[List[str]] = None, + ) -> None: """ Initialize a Completions object. @@ -4077,8 +4497,8 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if (completions := _dict.get('completions')) is not None: + args['completions'] = completions return cls(**args) @classmethod @@ -4112,25 +4532,27 @@ def __ne__(self, other: 'Completions') -> bool: return not self == other -class ComponentSettingsAggregation(): +class ComponentSettingsAggregation: """ Display settings for aggregations. - :attr str name: (optional) Identifier used to map aggregation settings to + :param str name: (optional) Identifier used to map aggregation settings to aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is allowed to select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when + :param str visualization_type: (optional) Type of visualization to use when rendering the aggregation. """ - def __init__(self, - *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + label: Optional[str] = None, + multiple_selections_allowed: Optional[bool] = None, + visualization_type: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsAggregation object. @@ -4151,15 +4573,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': """Initialize a ComponentSettingsAggregation object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (label := _dict.get('label')) is not None: + args['label'] = label + if (multiple_selections_allowed := + _dict.get('multiple_selections_allowed')) is not None: + args['multiple_selections_allowed'] = multiple_selections_allowed + if (visualization_type := _dict.get('visualization_type')) is not None: + args['visualization_type'] = visualization_type return cls(**args) @classmethod @@ -4206,26 +4628,29 @@ class VisualizationTypeEnum(str, Enum): """ Type of visualization to use when rendering the aggregation. """ + AUTO = 'auto' FACET_TABLE = 'facet_table' WORD_CLOUD = 'word_cloud' MAP = 'map' -class ComponentSettingsFieldsShown(): +class ComponentSettingsFieldsShown: """ Fields shown in the results section of the UI. - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. """ - def __init__(self, - *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: - """ - Initialize a ComponentSettingsFieldsShown object. + def __init__( + self, + *, + body: Optional['ComponentSettingsFieldsShownBody'] = None, + title: Optional['ComponentSettingsFieldsShownTitle'] = None, + ) -> None: + """ + Initialize a ComponentSettingsFieldsShown object. :param ComponentSettingsFieldsShownBody body: (optional) Body label. :param ComponentSettingsFieldsShownTitle title: (optional) Title label. @@ -4237,12 +4662,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody.from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle.from_dict( - _dict.get('title')) + if (body := _dict.get('body')) is not None: + args['body'] = ComponentSettingsFieldsShownBody.from_dict(body) + if (title := _dict.get('title')) is not None: + args['title'] = ComponentSettingsFieldsShownTitle.from_dict(title) return cls(**args) @classmethod @@ -4284,15 +4707,20 @@ def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: return not self == other -class ComponentSettingsFieldsShownBody(): +class ComponentSettingsFieldsShownBody: """ Body label. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + def __init__( + self, + *, + use_passage: Optional[bool] = None, + field: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsFieldsShownBody object. @@ -4306,10 +4734,10 @@ def __init__(self, *, use_passage: bool = None, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (use_passage := _dict.get('use_passage')) is not None: + args['use_passage'] = use_passage + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -4345,14 +4773,18 @@ def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: return not self == other -class ComponentSettingsFieldsShownTitle(): +class ComponentSettingsFieldsShownTitle: """ Title label. - :attr str field: (optional) Use a specific field as the title. + :param str field: (optional) Use a specific field as the title. """ - def __init__(self, *, field: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsFieldsShownTitle object. @@ -4364,8 +4796,8 @@ def __init__(self, *, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -4399,28 +4831,29 @@ def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: return not self == other -class ComponentSettingsResponse(): +class ComponentSettingsResponse: """ The default component settings for this project. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is + :param bool autocomplete: (optional) Whether or not autocomplete is enabled. + :param bool structured_search: (optional) Whether or not structured search is enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + self, + *, + fields_shown: Optional['ComponentSettingsFieldsShown'] = None, + autocomplete: Optional[bool] = None, + structured_search: Optional[bool] = None, + results_per_page: Optional[int] = None, + aggregations: Optional[List['ComponentSettingsAggregation']] = None, + ) -> None: """ Initialize a ComponentSettingsResponse object. @@ -4444,19 +4877,18 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - if 'fields_shown' in _dict: + if (fields_shown := _dict.get('fields_shown')) is not None: args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: + fields_shown) + if (autocomplete := _dict.get('autocomplete')) is not None: + args['autocomplete'] = autocomplete + if (structured_search := _dict.get('structured_search')) is not None: + args['structured_search'] = structured_search + if (results_per_page := _dict.get('results_per_page')) is not None: + args['results_per_page'] = results_per_page + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(v) - for v in _dict.get('aggregations') + ComponentSettingsAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -4510,36 +4942,36 @@ def __ne__(self, other: 'ComponentSettingsResponse') -> bool: return not self == other -class CreateDocumentClassifier(): +class CreateDocumentClassifier: """ An object that manages the settings and data that is required to train a document classification model. - :attr str name: A human-readable name of the document classifier. - :attr str description: (optional) A description of the document classifier. - :attr str language: The language of the training data that is associated with + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param str language: The language of the training data that is associated with the document classifier. Language is specified by using the ISO 639-1 language code, such as `en` for English or `ja` for Japanese. - :attr str answer_field: The name of the field from the training and test data + :param str answer_field: The name of the field from the training and test data that contains the classification labels. - :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of enrichments to apply to the data that is used to train and test the document classifier. The output from the enrichments is used as features by the classifier to classify the document content both during training and at run time. - :attr ClassifierFederatedModel federated_classification: (optional) An object + :param ClassifierFederatedModel federated_classification: (optional) An object with details for creating federated document classifier models. """ def __init__( - self, - name: str, - language: str, - answer_field: str, - *, - description: str = None, - enrichments: List['DocumentClassifierEnrichment'] = None, - federated_classification: 'ClassifierFederatedModel' = None + self, + name: str, + language: str, + answer_field: str, + *, + description: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, ) -> None: """ Initialize a CreateDocumentClassifier object. @@ -4571,35 +5003,35 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': """Initialize a CreateDocumentClassifier object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in CreateDocumentClassifier JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in CreateDocumentClassifier JSON' ) - if 'answer_field' in _dict: - args['answer_field'] = _dict.get('answer_field') + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field else: raise ValueError( 'Required property \'answer_field\' not present in CreateDocumentClassifier JSON' ) - if 'enrichments' in _dict: + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(v) - for v in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) for v in enrichments ] - if 'federated_classification' in _dict: + if (federated_classification := + _dict.get('federated_classification')) is not None: args[ 'federated_classification'] = ClassifierFederatedModel.from_dict( - _dict.get('federated_classification')) + federated_classification) return cls(**args) @classmethod @@ -4656,13 +5088,13 @@ def __ne__(self, other: 'CreateDocumentClassifier') -> bool: return not self == other -class CreateEnrichment(): +class CreateEnrichment: """ Information about a specific enrichment. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. The following types are + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following types are supported: * `classifier`: Creates a document classifier enrichment from a document classifier model that you create by using the [Document classifier @@ -4681,17 +5113,27 @@ class CreateEnrichment(): * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. - :attr EnrichmentOptions options: (optional) An object that contains options for + * `webhook`: Connects to an external enrichment application by using a webhook. + The feature is available from IBM Cloud-managed instances only. The external + enrichment feature is beta functionality. Beta features are not supported by the + SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not + supported by the SDKs. + :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a CreateEnrichment object. @@ -4716,6 +5158,14 @@ def __init__(self, * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a + webhook. The feature is available from IBM Cloud-managed instances only. + The external enrichment feature is beta functionality. Beta features are + not supported by the SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in + your documents. This feature is available in IBM Cloud-managed instances + only. The sentence classifier feature is beta functionality. Beta features + are not supported by the SDKs. :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments @@ -4730,14 +5180,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -4799,55 +5249,68 @@ class TypeEnum(str, Enum): * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a webhook. + The feature is available from IBM Cloud-managed instances only. The external + enrichment feature is beta functionality. Beta features are not supported by the + SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not supported + by the SDKs. """ + CLASSIFIER = 'classifier' DICTIONARY = 'dictionary' REGULAR_EXPRESSION = 'regular_expression' UIMA_ANNOTATOR = 'uima_annotator' RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' -class DefaultQueryParams(): +class DefaultQueryParams: """ Default query parameters for this project. - :attr List[str] collection_ids: (optional) An array of collection identifiers to - query. If empty or omitted all collections in the project are queried. - :attr DefaultQueryParamsPassages passages: (optional) Default settings + :param List[str] collection_ids: (optional) An array of collection identifiers + to query. If empty or omitted all collections in the project are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings configuration for passage search options. - :attr DefaultQueryParamsTableResults table_results: (optional) Default project + :param DefaultQueryParamsTableResults table_results: (optional) Default project query settings for table results. - :attr str aggregation: (optional) A string representing the default aggregation + :param str aggregation: (optional) A string representing the default aggregation query for the project. - :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) Object that contains suggested refinement settings. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + :param bool spelling_suggestions: (optional) When `true`, a spelling suggestions for the query are returned by default. - :attr bool highlight: (optional) When `true`, highlights for the query are + :param bool highlight: (optional) When `true`, highlights for the query are returned by default. - :attr int count: (optional) The number of document results returned by default. - :attr str sort: (optional) A comma separated list of document fields to sort + :param int count: (optional) The number of document results returned by default. + :param str sort: (optional) A comma separated list of document fields to sort results by default. - :attr List[str] return_: (optional) An array of field names to return in + :param List[str] return_: (optional) An array of field names to return in document results if present by default. """ - def __init__(self, - *, - collection_ids: List[str] = None, - passages: 'DefaultQueryParamsPassages' = None, - table_results: 'DefaultQueryParamsTableResults' = None, - aggregation: str = None, - suggested_refinements: - 'DefaultQueryParamsSuggestedRefinements' = None, - spelling_suggestions: bool = None, - highlight: bool = None, - count: int = None, - sort: str = None, - return_: List[str] = None) -> None: + def __init__( + self, + *, + collection_ids: Optional[List[str]] = None, + passages: Optional['DefaultQueryParamsPassages'] = None, + table_results: Optional['DefaultQueryParamsTableResults'] = None, + aggregation: Optional[str] = None, + suggested_refinements: Optional[ + 'DefaultQueryParamsSuggestedRefinements'] = None, + spelling_suggestions: Optional[bool] = None, + highlight: Optional[bool] = None, + count: Optional[int] = None, + sort: Optional[str] = None, + return_: Optional[List[str]] = None, + ) -> None: """ Initialize a DefaultQueryParams object. @@ -4890,30 +5353,31 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - if 'collection_ids' in _dict: - args['collection_ids'] = _dict.get('collection_ids') - if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages.from_dict( - _dict.get('passages')) - if 'table_results' in _dict: + if (collection_ids := _dict.get('collection_ids')) is not None: + args['collection_ids'] = collection_ids + if (passages := _dict.get('passages')) is not None: + args['passages'] = DefaultQueryParamsPassages.from_dict(passages) + if (table_results := _dict.get('table_results')) is not None: args['table_results'] = DefaultQueryParamsTableResults.from_dict( - _dict.get('table_results')) - if 'aggregation' in _dict: - args['aggregation'] = _dict.get('aggregation') - if 'suggested_refinements' in _dict: + table_results) + if (aggregation := _dict.get('aggregation')) is not None: + args['aggregation'] = aggregation + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: args[ 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( - _dict.get('suggested_refinements')) - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'sort' in _dict: - args['sort'] = _dict.get('sort') - if 'return' in _dict: - args['return_'] = _dict.get('return') + suggested_refinements) + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (count := _dict.get('count')) is not None: + args['count'] = count + if (sort := _dict.get('sort')) is not None: + args['sort'] = sort + if (return_ := _dict.get('return')) is not None: + args['return_'] = return_ return cls(**args) @classmethod @@ -4978,32 +5442,34 @@ def __ne__(self, other: 'DefaultQueryParams') -> bool: return not self == other -class DefaultQueryParamsPassages(): +class DefaultQueryParamsPassages: """ Default settings configuration for passage search options. - :attr bool enabled: (optional) When `true`, a passage search is performed by + :param bool enabled: (optional) When `true`, a passage search is performed by default. - :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perform the + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the passage search on. - :attr int characters: (optional) The approximate number of characters that each + :param int characters: (optional) The approximate number of characters that each returned passage will contain. - :attr bool per_document: (optional) When `true` the number of passages that can + :param bool per_document: (optional) When `true` the number of passages that can be returned from a single document is restricted to the *max_per_document* value. - :attr int max_per_document: (optional) The default maximum number of passages + :param int max_per_document: (optional) The default maximum number of passages that can be taken from a single document as the result of a passage query. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - fields: List[str] = None, - characters: int = None, - per_document: bool = None, - max_per_document: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + fields: Optional[List[str]] = None, + characters: Optional[int] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsPassages object. @@ -5032,18 +5498,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document return cls(**args) @classmethod @@ -5088,19 +5554,24 @@ def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: return not self == other -class DefaultQueryParamsSuggestedRefinements(): +class DefaultQueryParamsSuggestedRefinements: """ Object that contains suggested refinement settings. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr bool enabled: (optional) When `true`, suggested refinements for the query + :param bool enabled: (optional) When `true`, suggested refinements for the query are returned by default. - :attr int count: (optional) The number of suggested refinements to return by + :param int count: (optional) The number of suggested refinements to return by default. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsSuggestedRefinements object. @@ -5116,10 +5587,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -5155,22 +5626,24 @@ def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: return not self == other -class DefaultQueryParamsTableResults(): +class DefaultQueryParamsTableResults: """ Default project query settings for table results. - :attr bool enabled: (optional) When `true`, a table results for the query are + :param bool enabled: (optional) When `true`, a table results for the query are returned by default. - :attr int count: (optional) The number of table results to return by default. - :attr int per_document: (optional) The number of table results to include in + :param int count: (optional) The number of table results to return by default. + :param int per_document: (optional) The number of table results to include in each result document. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - per_document: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + per_document: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsTableResults object. @@ -5189,12 +5662,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document return cls(**args) @classmethod @@ -5232,16 +5705,21 @@ def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: return not self == other -class DeleteDocumentResponse(): +class DeleteDocumentResponse: """ Information returned when a document is deleted. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document has the status deleted. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5256,10 +5734,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5298,22 +5776,28 @@ class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ + DELETED = 'deleted' -class DocumentAccepted(): +class DocumentAccepted: """ Information returned after an uploaded document is accepted. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str status: (optional) Status of the document in the ingestion process. A + :param str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DocumentAccepted object. @@ -5331,10 +5815,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5375,26 +5859,29 @@ class StatusEnum(str, Enum): returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ + PROCESSING = 'processing' PENDING = 'pending' -class DocumentAttribute(): +class DocumentAttribute: """ List of document attributes. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ Initialize a DocumentAttribute object. @@ -5412,13 +5899,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod @@ -5459,53 +5945,53 @@ def __ne__(self, other: 'DocumentAttribute') -> bool: return not self == other -class DocumentClassifier(): +class DocumentClassifier: """ Information about a document classifier. - :attr str classifier_id: (optional) A unique identifier of the document + :param str classifier_id: (optional) A unique identifier of the document classifier. - :attr str name: A human-readable name of the document classifier. - :attr str description: (optional) A description of the document classifier. - :attr datetime created: (optional) The date that the document classifier was + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param datetime created: (optional) The date that the document classifier was created. - :attr str language: (optional) The language of the training data that is + :param str language: (optional) The language of the training data that is associated with the document classifier. Language is specified by using the ISO 639-1 language code, such as `en` for English or `ja` for Japanese. - :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of enrichments to apply to the data that is used to train and test the document classifier. The output from the enrichments is used as features by the classifier to classify the document content both during training and at run time. - :attr List[str] recognized_fields: (optional) An array of fields that are used + :param List[str] recognized_fields: (optional) An array of fields that are used to train the document classifier. The same set of fields must exist in the training data, the test data, and the documents where the resulting document classifier enrichment is applied at run time. - :attr str answer_field: (optional) The name of the field from the training and + :param str answer_field: (optional) The name of the field from the training and test data that contains the classification labels. - :attr str training_data_file: (optional) Name of the CSV file with training data - that is used to train the document classifier. - :attr str test_data_file: (optional) Name of the CSV file with data that is used - to test the document classifier. If no test data is provided, a subset of the - training data is used for testing purposes. - :attr ClassifierFederatedModel federated_classification: (optional) An object + :param str training_data_file: (optional) Name of the CSV file with training + data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that is + used to test the document classifier. If no test data is provided, a subset of + the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An object with details for creating federated document classifier models. """ def __init__( - self, - name: str, - *, - classifier_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['DocumentClassifierEnrichment'] = None, - recognized_fields: List[str] = None, - answer_field: str = None, - training_data_file: str = None, - test_data_file: str = None, - federated_classification: 'ClassifierFederatedModel' = None + self, + name: str, + *, + classifier_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + recognized_fields: Optional[List[str]] = None, + answer_field: Optional[str] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, ) -> None: """ Initialize a DocumentClassifier object. @@ -5551,37 +6037,37 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': """Initialize a DocumentClassifier object from a json dictionary.""" args = {} - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DocumentClassifier JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'enrichments' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(v) - for v in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) for v in enrichments ] - if 'recognized_fields' in _dict: - args['recognized_fields'] = _dict.get('recognized_fields') - if 'answer_field' in _dict: - args['answer_field'] = _dict.get('answer_field') - if 'training_data_file' in _dict: - args['training_data_file'] = _dict.get('training_data_file') - if 'test_data_file' in _dict: - args['test_data_file'] = _dict.get('test_data_file') - if 'federated_classification' in _dict: + if (recognized_fields := _dict.get('recognized_fields')) is not None: + args['recognized_fields'] = recognized_fields + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (federated_classification := + _dict.get('federated_classification')) is not None: args[ 'federated_classification'] = ClassifierFederatedModel.from_dict( - _dict.get('federated_classification')) + federated_classification) return cls(**args) @classmethod @@ -5652,16 +6138,21 @@ def __ne__(self, other: 'DocumentClassifier') -> bool: return not self == other -class DocumentClassifierEnrichment(): +class DocumentClassifierEnrichment: """ An object that describes enrichments that are applied to the training and test data that is used by the document classifier. - :attr str enrichment_id: A unique identifier of the enrichment. - :attr List[str] fields: An array of field names where the enrichment is applied. + :param str enrichment_id: A unique identifier of the enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - def __init__(self, enrichment_id: str, fields: List[str]) -> None: + def __init__( + self, + enrichment_id: str, + fields: List[str], + ) -> None: """ Initialize a DocumentClassifierEnrichment object. @@ -5676,14 +6167,14 @@ def __init__(self, enrichment_id: str, fields: List[str]) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentClassifierEnrichment': """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id else: raise ValueError( 'Required property \'enrichment_id\' not present in DocumentClassifierEnrichment JSON' ) - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields else: raise ValueError( 'Required property \'fields\' not present in DocumentClassifierEnrichment JSON' @@ -5723,46 +6214,48 @@ def __ne__(self, other: 'DocumentClassifierEnrichment') -> bool: return not self == other -class DocumentClassifierModel(): +class DocumentClassifierModel: """ Information about a document classifier model. - :attr str model_id: (optional) A unique identifier of the document classifier + :param str model_id: (optional) A unique identifier of the document classifier model. - :attr str name: A human-readable name of the document classifier model. - :attr str description: (optional) A description of the document classifier + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier model. - :attr datetime created: (optional) The date that the document classifier model + :param datetime created: (optional) The date that the document classifier model was created. - :attr datetime updated: (optional) The date that the document classifier model + :param datetime updated: (optional) The date that the document classifier model was last updated. - :attr str training_data_file: (optional) Name of the CSV file that contains the + :param str training_data_file: (optional) Name of the CSV file that contains the training data that is used to train the document classifier model. - :attr str test_data_file: (optional) Name of the CSV file that contains data + :param str test_data_file: (optional) Name of the CSV file that contains data that is used to test the document classifier model. If no test data is provided, a subset of the training data is used for testing purposes. - :attr str status: (optional) The status of the training run. - :attr ClassifierModelEvaluation evaluation: (optional) An object that contains + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that contains information about a trained document classifier model. - :attr str enrichment_id: (optional) A unique identifier of the enrichment that + :param str enrichment_id: (optional) A unique identifier of the enrichment that is generated by this document classifier model. - :attr datetime deployed_at: (optional) The date that the document classifier + :param datetime deployed_at: (optional) The date that the document classifier model was deployed. """ - def __init__(self, - name: str, - *, - model_id: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - training_data_file: str = None, - test_data_file: str = None, - status: str = None, - evaluation: 'ClassifierModelEvaluation' = None, - enrichment_id: str = None, - deployed_at: datetime = None) -> None: + def __init__( + self, + name: str, + *, + model_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + status: Optional[str] = None, + evaluation: Optional['ClassifierModelEvaluation'] = None, + enrichment_id: Optional[str] = None, + deployed_at: Optional[datetime] = None, + ) -> None: """ Initialize a DocumentClassifierModel object. @@ -5797,33 +6290,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModel': """Initialize a DocumentClassifierModel object from a json dictionary.""" args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DocumentClassifierModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'training_data_file' in _dict: - args['training_data_file'] = _dict.get('training_data_file') - if 'test_data_file' in _dict: - args['test_data_file'] = _dict.get('test_data_file') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'evaluation' in _dict: - args['evaluation'] = ClassifierModelEvaluation.from_dict( - _dict.get('evaluation')) - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'deployed_at' in _dict: - args['deployed_at'] = string_to_datetime(_dict.get('deployed_at')) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (status := _dict.get('status')) is not None: + args['status'] = status + if (evaluation := _dict.get('evaluation')) is not None: + args['evaluation'] = ClassifierModelEvaluation.from_dict(evaluation) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (deployed_at := _dict.get('deployed_at')) is not None: + args['deployed_at'] = string_to_datetime(deployed_at) return cls(**args) @classmethod @@ -5887,22 +6379,25 @@ class StatusEnum(str, Enum): """ The status of the training run. """ + TRAINING = 'training' AVAILABLE = 'available' FAILED = 'failed' -class DocumentClassifierModels(): +class DocumentClassifierModels: """ An object that contains a list of document classifier model definitions. - :attr List[DocumentClassifierModel] models: (optional) An array of document + :param List[DocumentClassifierModel] models: (optional) An array of document classifier model definitions. """ - def __init__(self, - *, - models: List['DocumentClassifierModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['DocumentClassifierModel']] = None, + ) -> None: """ Initialize a DocumentClassifierModels object. @@ -5915,10 +6410,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': """Initialize a DocumentClassifierModels object from a json dictionary.""" args = {} - if 'models' in _dict: + if (models := _dict.get('models')) is not None: args['models'] = [ - DocumentClassifierModel.from_dict(v) - for v in _dict.get('models') + DocumentClassifierModel.from_dict(v) for v in models ] return cls(**args) @@ -5959,17 +6453,19 @@ def __ne__(self, other: 'DocumentClassifierModels') -> bool: return not self == other -class DocumentClassifiers(): +class DocumentClassifiers: """ An object that contains a list of document classifier definitions. - :attr List[DocumentClassifier] classifiers: (optional) An array of document + :param List[DocumentClassifier] classifiers: (optional) An array of document classifier definitions. """ - def __init__(self, - *, - classifiers: List['DocumentClassifier'] = None) -> None: + def __init__( + self, + *, + classifiers: Optional[List['DocumentClassifier']] = None, + ) -> None: """ Initialize a DocumentClassifiers object. @@ -5982,10 +6478,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': """Initialize a DocumentClassifiers object from a json dictionary.""" args = {} - if 'classifiers' in _dict: + if (classifiers := _dict.get('classifiers')) is not None: args['classifiers'] = [ - DocumentClassifier.from_dict(v) - for v in _dict.get('classifiers') + DocumentClassifier.from_dict(v) for v in classifiers ] return cls(**args) @@ -6026,51 +6521,53 @@ def __ne__(self, other: 'DocumentClassifiers') -> bool: return not self == other -class DocumentDetails(): +class DocumentDetails: """ Information about a document. - :attr str document_id: (optional) The unique identifier of the document. - :attr datetime created: (optional) Date and time that the document is added to + :param str document_id: (optional) The unique identifier of the document. + :param datetime created: (optional) Date and time that the document is added to the collection. For a child document, the date and time when the process that generates the child document runs. The date-time format is `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date and time that the document is finished + :param datetime updated: (optional) Date and time that the document is finished being processed and is indexed. This date changes whenever the document is reprocessed, including for enrichment changes. The date-time format is `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr str status: (optional) The status of the ingestion of the document. The + :param str status: (optional) The status of the ingestion of the document. The possible values are: * `available`: Ingestion is finished and the document is indexed. * `failed`: Ingestion is finished, but the document is not indexed because of an error. * `pending`: The document is uploaded, but the ingestion process is not started. * `processing`: Ingestion is in progress. - :attr List[Notice] notices: (optional) Array of JSON objects for notices, + :param List[Notice] notices: (optional) Array of JSON objects for notices, meaning warning or error messages, that are produced by the document ingestion process. The array does not include notices that are produced for child documents that are generated when a document is processed. - :attr DocumentDetailsChildren children: (optional) Information about the child + :param DocumentDetailsChildren children: (optional) Information about the child documents that are generated from a single document during ingestion or other processing. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file, such as + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file, such as `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. - :attr str sha256: (optional) The SHA-256 hash of the original source file. The + :param str sha256: (optional) The SHA-256 hash of the original source file. The hash is formatted as a hexadecimal string. """ - def __init__(self, - *, - document_id: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - notices: List['Notice'] = None, - children: 'DocumentDetailsChildren' = None, - filename: str = None, - file_type: str = None, - sha256: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + notices: Optional[List['Notice']] = None, + children: Optional['DocumentDetailsChildren'] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha256: Optional[str] = None, + ) -> None: """ Initialize a DocumentDetails object. @@ -6110,27 +6607,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentDetails': """Initialize a DocumentDetails object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'children' in _dict: - args['children'] = DocumentDetailsChildren.from_dict( - _dict.get('children')) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha256' in _dict: - args['sha256'] = _dict.get('sha256') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (children := _dict.get('children')) is not None: + args['children'] = DocumentDetailsChildren.from_dict(children) + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha256 := _dict.get('sha256')) is not None: + args['sha256'] = sha256 return cls(**args) @classmethod @@ -6198,24 +6692,30 @@ class StatusEnum(str, Enum): * `pending`: The document is uploaded, but the ingestion process is not started. * `processing`: Ingestion is in progress. """ + AVAILABLE = 'available' FAILED = 'failed' PENDING = 'pending' PROCESSING = 'processing' -class DocumentDetailsChildren(): +class DocumentDetailsChildren: """ Information about the child documents that are generated from a single document during ingestion or other processing. - :attr bool have_notices: (optional) Indicates whether the child documents have + :param bool have_notices: (optional) Indicates whether the child documents have any notices. The value is `false` if the document does not have child documents. - :attr int count: (optional) Number of child documents. The value is `0` when + :param int count: (optional) Number of child documents. The value is `0` when processing of the document doesn't generate any child documents. """ - def __init__(self, *, have_notices: bool = None, count: int = None) -> None: + def __init__( + self, + *, + have_notices: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a DocumentDetailsChildren object. @@ -6232,10 +6732,10 @@ def __init__(self, *, have_notices: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentDetailsChildren': """Initialize a DocumentDetailsChildren object from a json dictionary.""" args = {} - if 'have_notices' in _dict: - args['have_notices'] = _dict.get('have_notices') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (have_notices := _dict.get('have_notices')) is not None: + args['have_notices'] = have_notices + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -6271,26 +6771,28 @@ def __ne__(self, other: 'DocumentDetailsChildren') -> bool: return not self == other -class Enrichment(): +class Enrichment: """ Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for + :param str enrichment_id: (optional) The unique identifier of this enrichment. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - enrichment_id: str = None, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a Enrichment object. @@ -6312,16 +6814,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -6370,6 +6872,7 @@ class TypeEnum(str, Enum): """ The type of this enrichment. """ + PART_OF_SPEECH = 'part_of_speech' SENTIMENT = 'sentiment' NATURAL_LANGUAGE_UNDERSTANDING = 'natural_language_understanding' @@ -6379,56 +6882,84 @@ class TypeEnum(str, Enum): RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' CLASSIFIER = 'classifier' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' -class EnrichmentOptions(): +class EnrichmentOptions: """ An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. - :attr List[str] languages: (optional) An array of supported languages for this + :param List[str] languages: (optional) An array of supported languages for this enrichment. When creating an enrichment, only specify a language that is used by the model or in the dictionary. Required when **type** is `dictionary`. Optional when **type** is `rule_based`. Not valid when creating any other type of enrichment. - :attr str entity_type: (optional) The name of the entity type. This value is + :param str entity_type: (optional) The name of the entity type. This value is used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. - :attr str regular_expression: (optional) The regular expression to apply for + :param str regular_expression: (optional) The regular expression to apply for this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. - :attr str result_field: (optional) The name of the result document field that + :param str result_field: (optional) The name of the result document field that this enrichment creates. Required when **type** is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. - :attr str classifier_id: (optional) A unique identifier of the document + :param str classifier_id: (optional) A unique identifier of the document classifier. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. - :attr str model_id: (optional) A unique identifier of the document classifier + :param str model_id: (optional) A unique identifier of the document classifier model. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. - :attr float confidence_threshold: (optional) Specifies a threshold. Only classes - with evaluation confidence scores that are higher than the specified threshold - are included in the output. Optional when **type** is `classifier`. Not valid - when creating any other type of enrichment. - :attr int top_k: (optional) Evaluates only the classes that fall in the top set + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the specified + threshold are included in the output. Optional when **type** is `classifier`. + Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the top set of results when ranked by confidence. For example, if set to `5`, then the top five classes for each document are evaluated. If set to 0, the **confidence_threshold** is used to determine the predicted classes. Optional when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with https) + for the webhook. Required when type is `webhook`. Not valid when creating any + other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` format. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param str secret: (optional) A private key can be included in the request to + authenticate with the external service. The maximum length is 1,024 characters. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with the + HTTP request. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of the + text's location with this encoding type in documents. Use the same location + encoding type in both Discovery and external enrichment for a document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. Optional + when `type` is `webhook`. Not valid when creating any other type of enrichment. """ - def __init__(self, - *, - languages: List[str] = None, - entity_type: str = None, - regular_expression: str = None, - result_field: str = None, - classifier_id: str = None, - model_id: str = None, - confidence_threshold: float = None, - top_k: int = None) -> None: + def __init__( + self, + *, + languages: Optional[List[str]] = None, + entity_type: Optional[str] = None, + regular_expression: Optional[str] = None, + result_field: Optional[str] = None, + classifier_id: Optional[str] = None, + model_id: Optional[str] = None, + confidence_threshold: Optional[float] = None, + top_k: Optional[int] = None, + url: Optional[str] = None, + version: Optional[str] = None, + secret: Optional[str] = None, + headers_: Optional['WebhookHeader'] = None, + location_encoding: Optional[str] = None, + ) -> None: """ Initialize a EnrichmentOptions object. @@ -6463,6 +6994,27 @@ def __init__(self, **confidence_threshold** is used to determine the predicted classes. Optional when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with + https) for the webhook. Required when type is `webhook`. Not valid when + creating any other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` + format. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str secret: (optional) A private key can be included in the request + to authenticate with the external service. The maximum length is 1,024 + characters. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with + the HTTP request. Optional when `type` is `webhook`. Not valid when + creating any other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of + the text's location with this encoding type in documents. Use the same + location encoding type in both Discovery and external enrichment for a + document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. + Optional when `type` is `webhook`. Not valid when creating any other type + of enrichment. """ self.languages = languages self.entity_type = entity_type @@ -6472,27 +7024,43 @@ def __init__(self, self.model_id = model_id self.confidence_threshold = confidence_threshold self.top_k = top_k + self.url = url + self.version = version + self.secret = secret + self.headers_ = headers_ + self.location_encoding = location_encoding @classmethod def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - if 'languages' in _dict: - args['languages'] = _dict.get('languages') - if 'entity_type' in _dict: - args['entity_type'] = _dict.get('entity_type') - if 'regular_expression' in _dict: - args['regular_expression'] = _dict.get('regular_expression') - if 'result_field' in _dict: - args['result_field'] = _dict.get('result_field') - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'confidence_threshold' in _dict: - args['confidence_threshold'] = _dict.get('confidence_threshold') - if 'top_k' in _dict: - args['top_k'] = _dict.get('top_k') + if (languages := _dict.get('languages')) is not None: + args['languages'] = languages + if (entity_type := _dict.get('entity_type')) is not None: + args['entity_type'] = entity_type + if (regular_expression := _dict.get('regular_expression')) is not None: + args['regular_expression'] = regular_expression + if (result_field := _dict.get('result_field')) is not None: + args['result_field'] = result_field + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (top_k := _dict.get('top_k')) is not None: + args['top_k'] = top_k + if (url := _dict.get('url')) is not None: + args['url'] = url + if (version := _dict.get('version')) is not None: + args['version'] = version + if (secret := _dict.get('secret')) is not None: + args['secret'] = secret + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = WebhookHeader.from_dict(headers_) + if (location_encoding := _dict.get('location_encoding')) is not None: + args['location_encoding'] = location_encoding return cls(**args) @classmethod @@ -6522,6 +7090,20 @@ def to_dict(self) -> Dict: _dict['confidence_threshold'] = self.confidence_threshold if hasattr(self, 'top_k') and self.top_k is not None: _dict['top_k'] = self.top_k + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'version') and self.version is not None: + _dict['version'] = self.version + if hasattr(self, 'secret') and self.secret is not None: + _dict['secret'] = self.secret + if hasattr(self, 'headers_') and self.headers_ is not None: + if isinstance(self.headers_, dict): + _dict['headers'] = self.headers_ + else: + _dict['headers'] = self.headers_.to_dict() + if hasattr(self, + 'location_encoding') and self.location_encoding is not None: + _dict['location_encoding'] = self.location_encoding return _dict def _to_dict(self): @@ -6543,15 +7125,19 @@ def __ne__(self, other: 'EnrichmentOptions') -> bool: return not self == other -class Enrichments(): +class Enrichments: """ An object that contains an array of enrichment definitions. - :attr List[Enrichment] enrichments: (optional) An array of enrichment + :param List[Enrichment] enrichments: (optional) An array of enrichment definitions. """ - def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: + def __init__( + self, + *, + enrichments: Optional[List['Enrichment']] = None, + ) -> None: """ Initialize a Enrichments object. @@ -6564,10 +7150,8 @@ def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Enrichments': """Initialize a Enrichments object from a json dictionary.""" args = {} - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(v) for v in _dict.get('enrichments') - ] + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] return cls(**args) @classmethod @@ -6607,7 +7191,7 @@ def __ne__(self, other: 'Enrichments') -> bool: return not self == other -class Expansion(): +class Expansion: """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions @@ -6616,17 +7200,19 @@ class Expansion(): * Multiword terms are supported only in bidirectional expansions. * Do not specify a term that is specified in the stop words list for the collection. - :attr List[str] input_terms: (optional) A list of terms that will be expanded + :param List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. - :attr List[str] expanded_terms: A list of terms that this expansion will be + :param List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, the list also functions as the input term list. """ - def __init__(self, - expanded_terms: List[str], - *, - input_terms: List[str] = None) -> None: + def __init__( + self, + expanded_terms: List[str], + *, + input_terms: Optional[List[str]] = None, + ) -> None: """ Initialize a Expansion object. @@ -6644,10 +7230,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} - if 'input_terms' in _dict: - args['input_terms'] = _dict.get('input_terms') - if 'expanded_terms' in _dict: - args['expanded_terms'] = _dict.get('expanded_terms') + if (input_terms := _dict.get('input_terms')) is not None: + args['input_terms'] = input_terms + if (expanded_terms := _dict.get('expanded_terms')) is not None: + args['expanded_terms'] = expanded_terms else: raise ValueError( 'Required property \'expanded_terms\' not present in Expansion JSON' @@ -6687,11 +7273,11 @@ def __ne__(self, other: 'Expansion') -> bool: return not self == other -class Expansions(): +class Expansions: """ The query expansion definitions for the specified collection. - :attr List[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as `bidirectional` or `unidirectional`. @@ -6705,7 +7291,10 @@ class Expansions(): repeat the input term in the expanded terms list. """ - def __init__(self, expansions: List['Expansion']) -> None: + def __init__( + self, + expansions: List['Expansion'], + ) -> None: """ Initialize a Expansions object. @@ -6729,10 +7318,8 @@ def __init__(self, expansions: List['Expansion']) -> None: def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} - if 'expansions' in _dict: - args['expansions'] = [ - Expansion.from_dict(v) for v in _dict.get('expansions') - ] + if (expansions := _dict.get('expansions')) is not None: + args['expansions'] = [Expansion.from_dict(v) for v in expansions] else: raise ValueError( 'Required property \'expansions\' not present in Expansions JSON' @@ -6776,21 +7363,23 @@ def __ne__(self, other: 'Expansions') -> bool: return not self == other -class Field(): +class Field: """ Object that contains field details. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - :attr str collection_id: (optional) The collection Id of the collection where + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection where the field was found. """ - def __init__(self, - *, - field: str = None, - type: str = None, - collection_id: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + type: Optional[str] = None, + collection_id: Optional[str] = None, + ) -> None: """ Initialize a Field object. @@ -6803,12 +7392,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (field := _dict.get('field')) is not None: + args['field'] = field + if (type := _dict.get('type')) is not None: + args['type'] = type + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id return cls(**args) @classmethod @@ -6850,6 +7439,7 @@ class TypeEnum(str, Enum): """ The type of the field. """ + NESTED = 'nested' STRING = 'string' DATE = 'date' @@ -6863,15 +7453,19 @@ class TypeEnum(str, Enum): BINARY = 'binary' -class ListCollectionsResponse(): +class ListCollectionsResponse: """ Response object that contains an array of collection details. - :attr List[Collection] collections: (optional) An array that contains + :param List[Collection] collections: (optional) An array that contains information about each collection in the project. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: + def __init__( + self, + *, + collections: Optional[List['Collection']] = None, + ) -> None: """ Initialize a ListCollectionsResponse object. @@ -6884,10 +7478,8 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(v) for v in _dict.get('collections') - ] + if (collections := _dict.get('collections')) is not None: + args['collections'] = [Collection.from_dict(v) for v in collections] return cls(**args) @classmethod @@ -6927,22 +7519,24 @@ def __ne__(self, other: 'ListCollectionsResponse') -> bool: return not self == other -class ListDocumentsResponse(): +class ListDocumentsResponse: """ Response object that contains an array of documents. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the document query. - :attr List[DocumentDetails] documents: (optional) An array that lists the + :param List[DocumentDetails] documents: (optional) An array that lists the documents in a collection. Only the document ID of each document is returned in the list. You can use the [Get document](#getdocument) method to get more information about an individual document. """ - def __init__(self, - *, - matching_results: int = None, - documents: List['DocumentDetails'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + documents: Optional[List['DocumentDetails']] = None, + ) -> None: """ Initialize a ListDocumentsResponse object. @@ -6960,11 +7554,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': """Initialize a ListDocumentsResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'documents' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (documents := _dict.get('documents')) is not None: args['documents'] = [ - DocumentDetails.from_dict(v) for v in _dict.get('documents') + DocumentDetails.from_dict(v) for v in documents ] return cls(**args) @@ -7008,7 +7602,7 @@ def __ne__(self, other: 'ListDocumentsResponse') -> bool: return not self == other -class ListFieldsResponse(): +class ListFieldsResponse: """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -7018,11 +7612,15 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr List[Field] fields: (optional) An array that contains information about + :param List[Field] fields: (optional) An array that contains information about each field in the collections. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__( + self, + *, + fields: Optional[List['Field']] = None, + ) -> None: """ Initialize a ListFieldsResponse object. @@ -7035,8 +7633,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] + if (fields := _dict.get('fields')) is not None: + args['fields'] = [Field.from_dict(v) for v in fields] return cls(**args) @classmethod @@ -7076,14 +7674,19 @@ def __ne__(self, other: 'ListFieldsResponse') -> bool: return not self == other -class ListProjectsResponse(): +class ListProjectsResponse: """ A list of projects in this instance. - :attr List[ProjectListDetails] projects: (optional) An array of project details. + :param List[ProjectListDetails] projects: (optional) An array of project + details. """ - def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + def __init__( + self, + *, + projects: Optional[List['ProjectListDetails']] = None, + ) -> None: """ Initialize a ListProjectsResponse object. @@ -7096,9 +7699,9 @@ def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - if 'projects' in _dict: + if (projects := _dict.get('projects')) is not None: args['projects'] = [ - ProjectListDetails.from_dict(v) for v in _dict.get('projects') + ProjectListDetails.from_dict(v) for v in projects ] return cls(**args) @@ -7139,23 +7742,28 @@ def __ne__(self, other: 'ListProjectsResponse') -> bool: return not self == other -class ModelEvaluationMacroAverage(): +class ModelEvaluationMacroAverage: """ A macro-average computes metric independently for each class and then takes the average. Class refers to the classification label that is specified in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, precision: float, recall: float, f1: float) -> None: + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a ModelEvaluationMacroAverage object. @@ -7176,20 +7784,20 @@ def __init__(self, precision: float, recall: float, f1: float) -> None: def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMacroAverage': """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" args = {} - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in ModelEvaluationMacroAverage JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in ModelEvaluationMacroAverage JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in ModelEvaluationMacroAverage JSON' @@ -7231,23 +7839,28 @@ def __ne__(self, other: 'ModelEvaluationMacroAverage') -> bool: return not self == other -class ModelEvaluationMicroAverage(): +class ModelEvaluationMicroAverage: """ A micro-average aggregates the contributions of all classes to compute the average metric. Classes refers to the classification labels that are specified in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, precision: float, recall: float, f1: float) -> None: + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a ModelEvaluationMicroAverage object. @@ -7268,20 +7881,20 @@ def __init__(self, precision: float, recall: float, f1: float) -> None: def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMicroAverage': """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" args = {} - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in ModelEvaluationMicroAverage JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in ModelEvaluationMicroAverage JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in ModelEvaluationMicroAverage JSON' @@ -7323,11 +7936,11 @@ def __ne__(self, other: 'ModelEvaluationMicroAverage') -> bool: return not self == other -class Notice(): +class Notice: """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have + :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs include: @@ -7342,28 +7955,30 @@ class Notice(): `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete list. Other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str collection_id: (optional) Unique identifier of the collection. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice occurred. - :attr str description: (optional) The description of the notice. + :param str description: (optional) The description of the notice. """ - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - collection_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: + def __init__( + self, + *, + notice_id: Optional[str] = None, + created: Optional[datetime] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + query_id: Optional[str] = None, + severity: Optional[str] = None, + step: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -7381,22 +7996,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (notice_id := _dict.get('notice_id')) is not None: + args['notice_id'] = notice_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (severity := _dict.get('severity')) is not None: + args['severity'] = severity + if (step := _dict.get('step')) is not None: + args['step'] = step + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -7451,29 +8066,35 @@ class SeverityEnum(str, Enum): """ Severity level of the notice. """ + WARNING = 'warning' ERROR = 'error' -class PerClassModelEvaluation(): +class PerClassModelEvaluation: """ An object that measures the metrics from a training run for each classification label separately. - :attr str name: Class name. Each class name is derived from a value in the + :param str name: Class name. Each class name is derived from a value in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, name: str, precision: float, recall: float, - f1: float) -> None: + def __init__( + self, + name: str, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a PerClassModelEvaluation object. @@ -7497,26 +8118,26 @@ def __init__(self, name: str, precision: float, recall: float, def from_dict(cls, _dict: Dict) -> 'PerClassModelEvaluation': """Initialize a PerClassModelEvaluation object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in PerClassModelEvaluation JSON' ) - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in PerClassModelEvaluation JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in PerClassModelEvaluation JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in PerClassModelEvaluation JSON' @@ -7560,34 +8181,36 @@ def __ne__(self, other: 'PerClassModelEvaluation') -> bool: return not self == other -class ProjectDetails(): +class ProjectDetails: """ Detailed information about the specified project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. - :attr DefaultQueryParams default_query_parameters: (optional) Default query + :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None, - default_query_parameters: 'DefaultQueryParams' = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + default_query_parameters: Optional['DefaultQueryParams'] = None, + ) -> None: """ Initialize a ProjectDetails object. @@ -7611,21 +8234,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectDetails': """Initialize a ProjectDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') - if 'default_query_parameters' in _dict: + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count + if (default_query_parameters := + _dict.get('default_query_parameters')) is not None: args['default_query_parameters'] = DefaultQueryParams.from_dict( - _dict.get('default_query_parameters')) + default_query_parameters) return cls(**args) @classmethod @@ -7691,6 +8316,7 @@ class TypeEnum(str, Enum): The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. """ + DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -7698,31 +8324,33 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetails(): +class ProjectListDetails: """ Details about a specific project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + ) -> None: """ Initialize a ProjectListDetails object. @@ -7743,18 +8371,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count return cls(**args) @classmethod @@ -7811,6 +8440,7 @@ class TypeEnum(str, Enum): The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. """ + DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -7818,39 +8448,41 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetailsRelevancyTrainingStatus(): +class ProjectListDetailsRelevancyTrainingStatus: """ Relevancy training status information for this project. - :attr str data_updated: (optional) When the training data was updated. - :attr int total_examples: (optional) The total number of examples. - :attr bool sufficient_label_diversity: (optional) When `true`, sufficient label + :param str data_updated: (optional) When the training data was updated. + :param int total_examples: (optional) The total number of examples. + :param bool sufficient_label_diversity: (optional) When `true`, sufficient label diversity is present to allow training for this project. - :attr bool processing: (optional) When `true`, the relevancy training is in + :param bool processing: (optional) When `true`, the relevancy training is in processing. - :attr bool minimum_examples_added: (optional) When `true`, the minimum number of - examples required to train has been met. - :attr str successfully_trained: (optional) The time that the most recent + :param bool minimum_examples_added: (optional) When `true`, the minimum number + of examples required to train has been met. + :param str successfully_trained: (optional) The time that the most recent successful training occurred. - :attr bool available: (optional) When `true`, relevancy training is available + :param bool available: (optional) When `true`, relevancy training is available when querying collections in the project. - :attr int notices: (optional) The number of notices generated during the + :param int notices: (optional) The number of notices generated during the relevancy training. - :attr bool minimum_queries_added: (optional) When `true`, the minimum number of + :param bool minimum_queries_added: (optional) When `true`, the minimum number of queries required to train has been met. """ - def __init__(self, - *, - data_updated: str = None, - total_examples: int = None, - sufficient_label_diversity: bool = None, - processing: bool = None, - minimum_examples_added: bool = None, - successfully_trained: str = None, - available: bool = None, - notices: int = None, - minimum_queries_added: bool = None) -> None: + def __init__( + self, + *, + data_updated: Optional[str] = None, + total_examples: Optional[int] = None, + sufficient_label_diversity: Optional[bool] = None, + processing: Optional[bool] = None, + minimum_examples_added: Optional[bool] = None, + successfully_trained: Optional[str] = None, + available: Optional[bool] = None, + notices: Optional[int] = None, + minimum_queries_added: Optional[bool] = None, + ) -> None: """ Initialize a ProjectListDetailsRelevancyTrainingStatus object. @@ -7886,25 +8518,28 @@ def from_dict(cls, _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} - if 'data_updated' in _dict: - args['data_updated'] = _dict.get('data_updated') - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'successfully_trained' in _dict: - args['successfully_trained'] = _dict.get('successfully_trained') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') + if (data_updated := _dict.get('data_updated')) is not None: + args['data_updated'] = data_updated + if (total_examples := _dict.get('total_examples')) is not None: + args['total_examples'] = total_examples + if (sufficient_label_diversity := + _dict.get('sufficient_label_diversity')) is not None: + args['sufficient_label_diversity'] = sufficient_label_diversity + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (minimum_examples_added := + _dict.get('minimum_examples_added')) is not None: + args['minimum_examples_added'] = minimum_examples_added + if (successfully_trained := + _dict.get('successfully_trained')) is not None: + args['successfully_trained'] = successfully_trained + if (available := _dict.get('available')) is not None: + args['available'] = available + if (notices := _dict.get('notices')) is not None: + args['notices'] = notices + if (minimum_queries_added := + _dict.get('minimum_queries_added')) is not None: + args['minimum_queries_added'] = minimum_queries_added return cls(**args) @classmethod @@ -7961,13 +8596,13 @@ def __ne__(self, return not self == other -class QueryAggregation(): +class QueryAggregation: """ An object that defines how to aggregate query results. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a QueryAggregation object. @@ -7994,22 +8629,20 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'QueryAggregation'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'QueryAggregationQueryTermAggregation', - 'QueryAggregationQueryGroupByAggregation', - 'QueryAggregationQueryHistogramAggregation', - 'QueryAggregationQueryTimesliceAggregation', - 'QueryAggregationQueryNestedAggregation', - 'QueryAggregationQueryFilterAggregation', - 'QueryAggregationQueryCalculationAggregation', - 'QueryAggregationQueryTopHitsAggregation', - 'QueryAggregationQueryPairAggregation', - 'QueryAggregationQueryTrendAggregation', - 'QueryAggregationQueryTopicAggregation' - ])) + msg = "Cannot convert dictionary into an instance of base class 'QueryAggregation'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) raise Exception(msg) @classmethod @@ -8050,34 +8683,36 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class QueryGroupByAggregationResult(): +class QueryGroupByAggregationResult: """ Result group for the `group_by` aggregation. - :attr str key: The condition that is met by the documents in this group. For + :param str key: The condition that is met by the documents in this group. For example, `YEARTXT<2000`. - :attr int matching_results: Number of documents that meet the query and + :param int matching_results: Number of documents that meet the query and condition. - :attr float relevancy: (optional) The relevancy for this group. Returned only if - `relevancy:true` is specified in the request. - :attr int total_matching_documents: (optional) Number of documents that meet the - condition in the whole set of documents in this collection. Returned only when - `relevancy:true` is specified in the request. - :attr float estimated_matching_results: (optional) The number of documents that + :param float relevancy: (optional) The relevancy for this group. Returned only + if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that meet + the condition in the whole set of documents in this collection. Returned only + when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents that are estimated to match the query and condition. Returned only when `relevancy:true` is specified in the request. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_results: float = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryGroupByAggregationResult object. @@ -8107,28 +8742,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryGroupByAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryGroupByAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_results' in _dict: - args['estimated_matching_results'] = _dict.get( - 'estimated_matching_results') - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8176,22 +8811,24 @@ def __ne__(self, other: 'QueryGroupByAggregationResult') -> bool: return not self == other -class QueryHistogramAggregationResult(): +class QueryHistogramAggregationResult: """ Histogram numeric interval result. - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryHistogramAggregationResult object. @@ -8209,20 +8846,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8261,30 +8898,30 @@ def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: return not self == other -class QueryLargePassages(): +class QueryLargePassages: """ Configuration for passage retrieval. - :attr bool enabled: (optional) A passages query that returns the most relevant + :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. - :attr bool per_document: (optional) If `true`, ranks the documents by document + :param bool per_document: (optional) If `true`, ranks the documents by document quality, and then returns the highest-ranked passages per document in a `document_passages` field for each document entry in the results list of the response. If `false`, ranks the passages from all of the documents by passage quality regardless of the document quality and returns them in a separate `passages` field in the response. - :attr int max_per_document: (optional) Maximum number of passages to return per + :param int max_per_document: (optional) Maximum number of passages to return per document in the result. Ignored if **passages.per_document** is `false`. - :attr List[str] fields: (optional) A list of fields to extract passages from. By - default, passages are extracted from the `text` and `title` fields only. If you - add this parameter and specify an empty list (`[]`) as its value, then the + :param List[str] fields: (optional) A list of fields to extract passages from. + By default, passages are extracted from the `text` and `title` fields only. If + you add this parameter and specify an empty list (`[]`) as its value, then the service searches all root-level fields for suitable passages. - :attr int count: (optional) The maximum number of passages to return. Ignored if - **passages.per_document** is `true`. - :attr int characters: (optional) The approximate number of characters that any + :param int count: (optional) The maximum number of passages to return. Ignored + if **passages.per_document** is `true`. + :param int characters: (optional) The approximate number of characters that any one passage will have. - :attr bool find_answers: (optional) When true, `answer` objects are returned as + :param bool find_answers: (optional) When true, `answer` objects are returned as part of each passage in the query results. The primary difference between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an `answer` is calculated by Discovery based on how @@ -8301,20 +8938,22 @@ class QueryLargePassages(): order of the highest confidence answer for each document and passage. The **find_answers** parameter is available only on managed instances of Discovery. - :attr int max_answers_per_passage: (optional) The number of `answer` objects to + :param int max_answers_per_passage: (optional) The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`. """ - def __init__(self, - *, - enabled: bool = None, - per_document: bool = None, - max_per_document: int = None, - fields: List[str] = None, - count: int = None, - characters: int = None, - find_answers: bool = None, - max_answers_per_passage: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + fields: Optional[List[str]] = None, + count: Optional[int] = None, + characters: Optional[int] = None, + find_answers: Optional[bool] = None, + max_answers_per_passage: Optional[int] = None, + ) -> None: """ Initialize a QueryLargePassages object. @@ -8375,23 +9014,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'max_answers_per_passage' in _dict: - args['max_answers_per_passage'] = _dict.get( - 'max_answers_per_passage') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (count := _dict.get('count')) is not None: + args['count'] = count + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (max_answers_per_passage := + _dict.get('max_answers_per_passage')) is not None: + args['max_answers_per_passage'] = max_answers_per_passage return cls(**args) @classmethod @@ -8441,27 +9080,29 @@ def __ne__(self, other: 'QueryLargePassages') -> bool: return not self == other -class QueryLargeSimilar(): +class QueryLargeSimilar: """ Finds results from documents that are similar to documents of interest. Use this parameter to add a *More like these* function to your search. You can include this parameter with or without a **query**, **filter** or **natural_language_query** parameter. - :attr bool enabled: (optional) When `true`, includes documents in the query + :param bool enabled: (optional) When `true`, includes documents in the query results that are similar to documents you specify. - :attr List[str] document_ids: (optional) The list of documents of interest. + :param List[str] document_ids: (optional) The list of documents of interest. Required if **enabled** is `true`. - :attr List[str] fields: (optional) Looks for similarities in the specified + :param List[str] fields: (optional) Looks for similarities in the specified subset of fields in the documents. If not specified, all of the document fields are used. """ - def __init__(self, - *, - enabled: bool = None, - document_ids: List[str] = None, - fields: List[str] = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + document_ids: Optional[List[str]] = None, + fields: Optional[List[str]] = None, + ) -> None: """ Initialize a QueryLargeSimilar object. @@ -8481,12 +9122,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargeSimilar': """Initialize a QueryLargeSimilar object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'document_ids' in _dict: - args['document_ids'] = _dict.get('document_ids') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (document_ids := _dict.get('document_ids')) is not None: + args['document_ids'] = document_ids + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields return cls(**args) @classmethod @@ -8524,18 +9165,23 @@ def __ne__(self, other: 'QueryLargeSimilar') -> bool: return not self == other -class QueryLargeSuggestedRefinements(): +class QueryLargeSuggestedRefinements: """ Configuration for suggested refinements. **Note**: The **suggested_refinements** parameter that identified dynamic facets from the data is deprecated. - :attr bool enabled: (optional) Whether to perform suggested refinements. - :attr int count: (optional) Maximum number of suggested refinements texts to be + :param bool enabled: (optional) Whether to perform suggested refinements. + :param int count: (optional) Maximum number of suggested refinements texts to be returned. The maximum is `100`. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeSuggestedRefinements object. @@ -8550,10 +9196,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8589,15 +9235,20 @@ def __ne__(self, other: 'QueryLargeSuggestedRefinements') -> bool: return not self == other -class QueryLargeTableResults(): +class QueryLargeTableResults: """ Configuration for table retrieval. - :attr bool enabled: (optional) Whether to enable table retrieval. - :attr int count: (optional) Maximum number of tables to return. + :param bool enabled: (optional) Whether to enable table retrieval. + :param int count: (optional) Maximum number of tables to return. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeTableResults object. @@ -8611,10 +9262,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8650,19 +9301,21 @@ def __ne__(self, other: 'QueryLargeTableResults') -> bool: return not self == other -class QueryNoticesResponse(): +class QueryNoticesResponse: """ Object that contains notice query results. - :attr int matching_results: (optional) The number of matching results. - :attr List[Notice] notices: (optional) Array of document results that match the + :param int matching_results: (optional) The number of matching results. + :param List[Notice] notices: (optional) Array of document results that match the query. """ - def __init__(self, - *, - matching_results: int = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a QueryNoticesResponse object. @@ -8677,12 +9330,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -8725,17 +9376,21 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other -class QueryPairAggregationResult(): +class QueryPairAggregationResult: """ Result for the `pair` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix that is returned contains a **relevancy** value that is calculated from the combination of each value from the first and second aggregations. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryPairAggregationResult object. @@ -8750,8 +9405,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryPairAggregationResult': """Initialize a QueryPairAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8785,40 +9440,43 @@ def __ne__(self, other: 'QueryPairAggregationResult') -> bool: return not self == other -class QueryResponse(): +class QueryResponse: """ A response that contains the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the query. Results that match due to a curation only are not counted in the total. - :attr List[QueryResult] results: (optional) Array of document results for the + :param List[QueryResult] results: (optional) Array of document results for the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregations for + :param List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) Suggested correction to the submitted + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) + :param List[QuerySuggestedRefinement] suggested_refinements: (optional) Deprecated: Array of suggested refinements. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr List[QueryTableResult] table_results: (optional) Array of table results. - :attr List[QueryResponsePassage] passages: (optional) Passages that best match + :param List[QueryTableResult] table_results: (optional) Array of table results. + :param List[QueryResponsePassage] passages: (optional) Passages that best match the query from across all of the collections in the project. Returned if **passages.per_document** is `false`. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None, - suggested_refinements: List['QuerySuggestedRefinement'] = None, - table_results: List['QueryTableResult'] = None, - passages: List['QueryResponsePassage'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + retrieval_details: Optional['RetrievalDetails'] = None, + suggested_query: Optional[str] = None, + suggested_refinements: Optional[ + List['QuerySuggestedRefinement']] = None, + table_results: Optional[List['QueryTableResult']] = None, + passages: Optional[List['QueryResponsePassage']] = None, + ) -> None: """ Initialize a QueryResponse object. @@ -8856,34 +9514,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'retrieval_details' in _dict: + if (retrieval_details := _dict.get('retrieval_details')) is not None: args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') - if 'suggested_refinements' in _dict: + retrieval_details) + if (suggested_query := _dict.get('suggested_query')) is not None: + args['suggested_query'] = suggested_query + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: args['suggested_refinements'] = [ QuerySuggestedRefinement.from_dict(v) - for v in _dict.get('suggested_refinements') + for v in suggested_refinements ] - if 'table_results' in _dict: + if (table_results := _dict.get('table_results')) is not None: args['table_results'] = [ - QueryTableResult.from_dict(v) - for v in _dict.get('table_results') + QueryTableResult.from_dict(v) for v in table_results ] - if 'passages' in _dict: + if (passages := _dict.get('passages')) is not None: args['passages'] = [ - QueryResponsePassage.from_dict(v) for v in _dict.get('passages') + QueryResponsePassage.from_dict(v) for v in passages ] return cls(**args) @@ -8969,39 +9625,41 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other -class QueryResponsePassage(): +class QueryResponsePassage: """ A passage query response. - :attr str passage_text: (optional) The content of the extracted passage. - :attr float passage_score: (optional) The confidence score of the passage's + :param str passage_text: (optional) The content of the extracted passage. + :param float passage_score: (optional) The confidence score of the passage's analysis. A higher score indicates greater confidence. The score is used to rank the passages from all documents and is returned only if **passages.per_document** is `false`. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr int start_offset: (optional) The position of the first character of the + :param str collection_id: (optional) The unique identifier of the collection. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr List[ResultPassageAnswer] answers: (optional) An array of extracted + :param List[ResultPassageAnswer] answers: (optional) An array of extracted answers to the specified query. Returned for natural language queries when **passages.per_document** is `false`. """ - def __init__(self, - *, - passage_text: str = None, - passage_score: float = None, - document_id: str = None, - collection_id: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - answers: List['ResultPassageAnswer'] = None) -> None: + def __init__( + self, + *, + passage_text: Optional[str] = None, + passage_score: Optional[float] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResponsePassage object. @@ -9037,23 +9695,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': """Initialize a QueryResponsePassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (passage_score := _dict.get('passage_score')) is not None: + args['passage_score'] = passage_score + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -9108,14 +9766,14 @@ def __ne__(self, other: 'QueryResponsePassage') -> bool: return not self == other -class QueryResult(): +class QueryResult: """ Result document for the specified query. - :attr str document_id: The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr QueryResultMetadata result_metadata: Metadata of a query result. - :attr List[QueryResultPassage] document_passages: (optional) Passages from the + :param str document_id: The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param QueryResultMetadata result_metadata: Metadata of a query result. + :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. """ @@ -9124,13 +9782,15 @@ class QueryResult(): _properties = frozenset( ['document_id', 'metadata', 'result_metadata', 'document_passages']) - def __init__(self, - document_id: str, - result_metadata: 'QueryResultMetadata', - *, - metadata: dict = None, - document_passages: List['QueryResultPassage'] = None, - **kwargs) -> None: + def __init__( + self, + document_id: str, + result_metadata: 'QueryResultMetadata', + *, + metadata: Optional[dict] = None, + document_passages: Optional[List['QueryResultPassage']] = None, + **kwargs, + ) -> None: """ Initialize a QueryResult object. @@ -9153,25 +9813,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in QueryResult JSON' ) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'result_metadata' in _dict: + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) else: raise ValueError( 'Required property \'result_metadata\' not present in QueryResult JSON' ) - if 'document_passages' in _dict: + if (document_passages := _dict.get('document_passages')) is not None: args['document_passages'] = [ - QueryResultPassage.from_dict(v) - for v in _dict.get('document_passages') + QueryResultPassage.from_dict(v) for v in document_passages ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -9250,15 +9909,15 @@ def __ne__(self, other: 'QueryResult') -> bool: return not self == other -class QueryResultMetadata(): +class QueryResultMetadata: """ Metadata of a query result. - :attr str document_retrieval_source: (optional) The document retrieval source + :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. - :attr str collection_id: The collection id associated with this training data + :param str collection_id: The collection id associated with this training data set. - :attr float confidence: (optional) The confidence score for the given result. + :param float confidence: (optional) The confidence score for the given result. Calculated based on how relevant the result is estimated to be. The score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model @@ -9267,11 +9926,13 @@ class QueryResultMetadata(): in the query. """ - def __init__(self, - collection_id: str, - *, - document_retrieval_source: str = None, - confidence: float = None) -> None: + def __init__( + self, + collection_id: str, + *, + document_retrieval_source: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a QueryResultMetadata object. @@ -9295,17 +9956,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - if 'document_retrieval_source' in _dict: - args['document_retrieval_source'] = _dict.get( - 'document_retrieval_source') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (document_retrieval_source := + _dict.get('document_retrieval_source')) is not None: + args['document_retrieval_source'] = document_retrieval_source + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in QueryResultMetadata JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9347,33 +10008,36 @@ class DocumentRetrievalSourceEnum(str, Enum): """ The document retrieval source that produced this search result. """ + SEARCH = 'search' CURATION = 'curation' -class QueryResultPassage(): +class QueryResultPassage: """ A passage query result. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers - to the specified query. Returned for natural language queries when + :param List[ResultPassageAnswer] answers: (optional) An arry of extracted + answers to the specified query. Returned for natural language queries when **passages.per_document** is `true`. """ - def __init__(self, - *, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - answers: List['ResultPassageAnswer'] = None) -> None: + def __init__( + self, + *, + passage_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResultPassage object. @@ -9398,17 +10062,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -9457,15 +10121,19 @@ def __ne__(self, other: 'QueryResultPassage') -> bool: return not self == other -class QuerySuggestedRefinement(): +class QuerySuggestedRefinement: """ A suggested additional query term or terms user to filter results. **Note**: The `suggested_refinements` parameter is deprecated. - :attr str text: (optional) The text used to filter. + :param str text: (optional) The text used to filter. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a QuerySuggestedRefinement object. @@ -9477,8 +10145,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -9512,30 +10180,32 @@ def __ne__(self, other: 'QuerySuggestedRefinement') -> bool: return not self == other -class QueryTableResult(): +class QueryTableResult: """ A tables whose content or context match a search query. - :attr str table_id: (optional) The identifier for the retrieved table. - :attr str source_document_id: (optional) The identifier of the document the + :param str table_id: (optional) The identifier for the retrieved table. + :param str source_document_id: (optional) The identifier of the document the table was retrieved from. - :attr str collection_id: (optional) The identifier of the collection the table + :param str collection_id: (optional) The identifier of the collection the table was retrieved from. - :attr str table_html: (optional) HTML snippet of the table info. - :attr int table_html_offset: (optional) The offset of the table html snippet in + :param str table_html: (optional) HTML snippet of the table info. + :param int table_html_offset: (optional) The offset of the table html snippet in the original document html. - :attr TableResultTable table: (optional) Full table object retrieved from Table + :param TableResultTable table: (optional) Full table object retrieved from Table Understanding Enrichment. """ - def __init__(self, - *, - table_id: str = None, - source_document_id: str = None, - collection_id: str = None, - table_html: str = None, - table_html_offset: int = None, - table: 'TableResultTable' = None) -> None: + def __init__( + self, + *, + table_id: Optional[str] = None, + source_document_id: Optional[str] = None, + collection_id: Optional[str] = None, + table_html: Optional[str] = None, + table_html_offset: Optional[int] = None, + table: Optional['TableResultTable'] = None, + ) -> None: """ Initialize a QueryTableResult object. @@ -9561,18 +10231,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} - if 'table_id' in _dict: - args['table_id'] = _dict.get('table_id') - if 'source_document_id' in _dict: - args['source_document_id'] = _dict.get('source_document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'table_html' in _dict: - args['table_html'] = _dict.get('table_html') - if 'table_html_offset' in _dict: - args['table_html_offset'] = _dict.get('table_html_offset') - if 'table' in _dict: - args['table'] = TableResultTable.from_dict(_dict.get('table')) + if (table_id := _dict.get('table_id')) is not None: + args['table_id'] = table_id + if (source_document_id := _dict.get('source_document_id')) is not None: + args['source_document_id'] = source_document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (table_html := _dict.get('table_html')) is not None: + args['table_html'] = table_html + if (table_html_offset := _dict.get('table_html_offset')) is not None: + args['table_html_offset'] = table_html_offset + if (table := _dict.get('table')) is not None: + args['table'] = TableResultTable.from_dict(table) return cls(**args) @classmethod @@ -9622,33 +10292,35 @@ def __ne__(self, other: 'QueryTableResult') -> bool: return not self == other -class QueryTermAggregationResult(): +class QueryTermAggregationResult: """ Top value result for the `term` aggregation. - :attr str key: Value of the field with a nonzero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy score for this result. Returned + :param str key: Value of the field with a nonzero frequency in the document set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy score for this result. Returned only if `relevancy:true` is specified in the request. - :attr int total_matching_documents: (optional) Number of documents in the + :param int total_matching_documents: (optional) Number of documents in the collection that contain the term in the specified field. Returned only when `relevancy:true` is specified in the request. - :attr float estimated_matching_results: (optional) Number of documents that are + :param float estimated_matching_results: (optional) Number of documents that are estimated to match the query and also meet the condition. Returned only when `relevancy:true` is specified in the request. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is combined with other aggregations in the request or is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_results: float = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTermAggregationResult object. @@ -9678,28 +10350,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTermAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_results' in _dict: - args['estimated_matching_results'] = _dict.get( - 'estimated_matching_results') - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9747,27 +10419,29 @@ def __ne__(self, other: 'QueryTermAggregationResult') -> bool: return not self == other -class QueryTimesliceAggregationResult(): +class QueryTimesliceAggregationResult: """ A timeslice interval segment. - :attr str key_as_string: String date value of the upper bound for the timeslice + :param str key_as_string: String date value of the upper bound for the timeslice interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval + :param int key: Numeric date value of the upper bound for the timeslice interval in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List[dict] = None) -> None: - """ + def __init__( + self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: + """ Initialize a QueryTimesliceAggregationResult object. :param str key_as_string: String date value of the upper bound for the @@ -9788,26 +10462,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = key_as_string else: raise ValueError( 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' ) - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9848,19 +10522,21 @@ def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: return not self == other -class QueryTopHitsAggregationResult(): +class QueryTopHitsAggregationResult: """ A query response that contains the matching documents for the preceding aggregations. - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results in an ordered - list. + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. """ - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: + def __init__( + self, + matching_results: int, + *, + hits: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopHitsAggregationResult object. @@ -9875,14 +10551,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') + if (hits := _dict.get('hits')) is not None: + args['hits'] = hits return cls(**args) @classmethod @@ -9919,17 +10595,21 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other -class QueryTopicAggregationResult(): +class QueryTopicAggregationResult: """ Result for the `topic` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term` or `group_by` and `timeslice`. Each element of the matrix that is returned contains a **topic_indicator** that is calculated from the combination of each aggregation value and segment of time. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopicAggregationResult object. @@ -9944,8 +10624,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryTopicAggregationResult': """Initialize a QueryTopicAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9979,17 +10659,21 @@ def __ne__(self, other: 'QueryTopicAggregationResult') -> bool: return not self == other -class QueryTrendAggregationResult(): +class QueryTrendAggregationResult: """ Result for the `trend` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term` or `group_by` and `timeslice`. Each element of the matrix that is returned contains a **trend_indicator** that is calculated from the combination of each aggregation value and segment of time. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTrendAggregationResult object. @@ -10004,8 +10688,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryTrendAggregationResult': """Initialize a QueryTrendAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -10039,26 +10723,28 @@ def __ne__(self, other: 'QueryTrendAggregationResult') -> bool: return not self == other -class ResultPassageAnswer(): +class ResultPassageAnswer: """ Object that contains a potential answer to the specified query. - :attr str answer_text: (optional) Answer text for the specified query as + :param str answer_text: (optional) Answer text for the specified query as identified by Discovery. - :attr int start_offset: (optional) The position of the first character of the + :param int start_offset: (optional) The position of the first character of the extracted answer in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted answer in the originating field. - :attr float confidence: (optional) An estimate of the probability that the + :param float confidence: (optional) An estimate of the probability that the answer is relevant. """ - def __init__(self, - *, - answer_text: str = None, - start_offset: int = None, - end_offset: int = None, - confidence: float = None) -> None: + def __init__( + self, + *, + answer_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ResultPassageAnswer object. @@ -10080,14 +10766,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ResultPassageAnswer': """Initialize a ResultPassageAnswer object from a json dictionary.""" args = {} - if 'answer_text' in _dict: - args['answer_text'] = _dict.get('answer_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (answer_text := _dict.get('answer_text')) is not None: + args['answer_text'] = answer_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -10127,11 +10813,11 @@ def __ne__(self, other: 'ResultPassageAnswer') -> bool: return not self == other -class RetrievalDetails(): +class RetrievalDetails: """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Identifies the document + :param str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the trained @@ -10139,7 +10825,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__( + self, + *, + document_retrieval_strategy: Optional[str] = None, + ) -> None: """ Initialize a RetrievalDetails object. @@ -10156,9 +10846,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if (document_retrieval_strategy := + _dict.get('document_retrieval_strategy')) is not None: + args['document_retrieval_strategy'] = document_retrieval_strategy return cls(**args) @classmethod @@ -10202,18 +10892,22 @@ class DocumentRetrievalStrategyEnum(str, Enum): is not used to return results, the **document_retrieval_strategy** is listed as `untrained`. """ + UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' -class StopWordList(): +class StopWordList: """ List of words to filter out of text that is submitted in queries. - :attr List[str] stopwords: List of stop words. + :param List[str] stopwords: List of stop words. """ - def __init__(self, stopwords: List[str]) -> None: + def __init__( + self, + stopwords: List[str], + ) -> None: """ Initialize a StopWordList object. @@ -10225,8 +10919,8 @@ def __init__(self, stopwords: List[str]) -> None: def from_dict(cls, _dict: Dict) -> 'StopWordList': """Initialize a StopWordList object from a json dictionary.""" args = {} - if 'stopwords' in _dict: - args['stopwords'] = _dict.get('stopwords') + if (stopwords := _dict.get('stopwords')) is not None: + args['stopwords'] = stopwords else: raise ValueError( 'Required property \'stopwords\' not present in StopWordList JSON' @@ -10264,58 +10958,58 @@ def __ne__(self, other: 'StopWordList') -> bool: return not self == other -class TableBodyCells(): +class TableBodyCells: """ Cells that are not table header, column header, or row header cells. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr List[TableRowHeaderIds] row_header_ids: (optional) A list of table row - header ids. - :attr List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row - header texts. - :attr List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :attr List[TableColumnHeaderIds] column_header_ids: (optional) A list of table - column header ids. - :attr List[TableColumnHeaderTexts] column_header_texts: (optional) A list of - table column header texts. - :attr List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: - (optional) A list of table column header texts normalized. - :attr List[DocumentAttribute] attributes: (optional) A list of document + :param List[str] row_header_ids: (optional) A list of ID values that represent + the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values that + are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of normalized + row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header values + that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of normalized + column header values that are associated with this body cell. + :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None, - row_header_ids: List['TableRowHeaderIds'] = None, - row_header_texts: List['TableRowHeaderTexts'] = None, - row_header_texts_normalized: List[ - 'TableRowHeaderTextsNormalized'] = None, - column_header_ids: List['TableColumnHeaderIds'] = None, - column_header_texts: List['TableColumnHeaderTexts'] = None, - column_header_texts_normalized: List[ - 'TableColumnHeaderTextsNormalized'] = None, - attributes: List['DocumentAttribute'] = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + row_header_ids: Optional[List[str]] = None, + row_header_texts: Optional[List[str]] = None, + row_header_texts_normalized: Optional[List[str]] = None, + column_header_ids: Optional[List[str]] = None, + column_header_texts: Optional[List[str]] = None, + column_header_texts_normalized: Optional[List[str]] = None, + attributes: Optional[List['DocumentAttribute']] = None, + ) -> None: """ Initialize a TableBodyCells object. @@ -10334,19 +11028,18 @@ def __init__(self, `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table - row header ids. - :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of - table row header texts. - :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of - table column header ids. - :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list - of table column header texts. - :param List[TableColumnHeaderTextsNormalized] - column_header_texts_normalized: (optional) A list of table column header - texts normalized. + :param List[str] row_header_ids: (optional) A list of ID values that + represent the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values + that are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of + normalized row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header + values that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of + normalized column header values that are associated with this body cell. :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ @@ -10369,54 +11062,39 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - if 'row_header_ids' in _dict: - args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(v) - for v in _dict.get('row_header_ids') - ] - if 'row_header_texts' in _dict: - args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(v) - for v in _dict.get('row_header_texts') - ] - if 'row_header_texts_normalized' in _dict: - args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized.from_dict(v) - for v in _dict.get('row_header_texts_normalized') - ] - if 'column_header_ids' in _dict: - args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(v) - for v in _dict.get('column_header_ids') - ] - if 'column_header_texts' in _dict: - args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(v) - for v in _dict.get('column_header_texts') - ] - if 'column_header_texts_normalized' in _dict: - args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized.from_dict(v) - for v in _dict.get('column_header_texts_normalized') - ] - if 'attributes' in _dict: + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end + if (row_header_ids := _dict.get('row_header_ids')) is not None: + args['row_header_ids'] = row_header_ids + if (row_header_texts := _dict.get('row_header_texts')) is not None: + args['row_header_texts'] = row_header_texts + if (row_header_texts_normalized := + _dict.get('row_header_texts_normalized')) is not None: + args['row_header_texts_normalized'] = row_header_texts_normalized + if (column_header_ids := _dict.get('column_header_ids')) is not None: + args['column_header_ids'] = column_header_ids + if (column_header_texts := + _dict.get('column_header_texts')) is not None: + args['column_header_texts'] = column_header_texts + if (column_header_texts_normalized := + _dict.get('column_header_texts_normalized')) is not None: + args[ + 'column_header_texts_normalized'] = column_header_texts_normalized + if (attributes := _dict.get('attributes')) is not None: args['attributes'] = [ - DocumentAttribute.from_dict(v) for v in _dict.get('attributes') + DocumentAttribute.from_dict(v) for v in attributes ] return cls(**args) @@ -10450,61 +11128,25 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - row_header_ids_list = [] - for v in self.row_header_ids: - if isinstance(v, dict): - row_header_ids_list.append(v) - else: - row_header_ids_list.append(v.to_dict()) - _dict['row_header_ids'] = row_header_ids_list + _dict['row_header_ids'] = self.row_header_ids if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: - row_header_texts_list = [] - for v in self.row_header_texts: - if isinstance(v, dict): - row_header_texts_list.append(v) - else: - row_header_texts_list.append(v.to_dict()) - _dict['row_header_texts'] = row_header_texts_list + _dict['row_header_texts'] = self.row_header_texts if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: - row_header_texts_normalized_list = [] - for v in self.row_header_texts_normalized: - if isinstance(v, dict): - row_header_texts_normalized_list.append(v) - else: - row_header_texts_normalized_list.append(v.to_dict()) _dict[ - 'row_header_texts_normalized'] = row_header_texts_normalized_list + 'row_header_texts_normalized'] = self.row_header_texts_normalized if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: - column_header_ids_list = [] - for v in self.column_header_ids: - if isinstance(v, dict): - column_header_ids_list.append(v) - else: - column_header_ids_list.append(v.to_dict()) - _dict['column_header_ids'] = column_header_ids_list + _dict['column_header_ids'] = self.column_header_ids if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: - column_header_texts_list = [] - for v in self.column_header_texts: - if isinstance(v, dict): - column_header_texts_list.append(v) - else: - column_header_texts_list.append(v.to_dict()) - _dict['column_header_texts'] = column_header_texts_list + _dict['column_header_texts'] = self.column_header_texts if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: - column_header_texts_normalized_list = [] - for v in self.column_header_texts_normalized: - if isinstance(v, dict): - column_header_texts_normalized_list.append(v) - else: - column_header_texts_normalized_list.append(v.to_dict()) _dict[ - 'column_header_texts_normalized'] = column_header_texts_normalized_list + 'column_header_texts_normalized'] = self.column_header_texts_normalized if hasattr(self, 'attributes') and self.attributes is not None: attributes_list = [] for v in self.attributes: @@ -10534,23 +11176,25 @@ def __ne__(self, other: 'TableBodyCells') -> bool: return not self == other -class TableCellKey(): +class TableCellKey: """ A key in a key-value pair. - :attr str cell_id: (optional) The unique ID of the key in the table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the key in the table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML + :param str text: (optional) The text content of the table cell without HTML markup. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a TableCellKey object. @@ -10569,13 +11213,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -10616,23 +11259,25 @@ def __ne__(self, other: 'TableCellKey') -> bool: return not self == other -class TableCellValues(): +class TableCellValues: """ A value in a key-value pair. - :attr str cell_id: (optional) The unique ID of the value in the table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the value in the table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML + :param str text: (optional) The text content of the table cell without HTML markup. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a TableCellValues object. @@ -10651,13 +11296,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellValues': """Initialize a TableCellValues object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -10698,221 +11342,51 @@ def __ne__(self, other: 'TableCellValues') -> bool: return not self == other -class TableColumnHeaderIds(): - """ - An array of values, each being the `id` value of a column header that is applicable to - the current cell. - - :attr str id: (optional) The `id` value of a column header. - """ - - def __init__(self, *, id: str = None) -> None: - """ - Initialize a TableColumnHeaderIds object. - - :param str id: (optional) The `id` value of a column header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': - """Initialize a TableColumnHeaderIds object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderIds object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderIds') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableColumnHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTexts(): - """ - An array of values, each being the `text` value of a column header that is applicable - to the current cell. - - :attr str text: (optional) The `text` value of a column header. - """ - - def __init__(self, *, text: str = None) -> None: - """ - Initialize a TableColumnHeaderTexts object. - - :param str text: (optional) The `text` value of a column header. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': - """Initialize a TableColumnHeaderTexts object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTexts object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderTexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderTexts') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableColumnHeaderTexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTextsNormalized(): - """ - If you provide customization input, the normalized version of the column header texts - according to the customization; otherwise, the same value as `column_header_texts`. - - :attr str text_normalized: (optional) The normalized version of a column header - text. - """ - - def __init__(self, *, text_normalized: str = None) -> None: - """ - Initialize a TableColumnHeaderTextsNormalized object. - - :param str text_normalized: (optional) The normalized version of a column - header text. - """ - self.text_normalized = text_normalized - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': - """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" - args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderTextsNormalized object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaders(): +class TableColumnHeaders: """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr dict location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of this cell from the input + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param str text_normalized: (optional) Normalized column header text. + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: dict = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableColumnHeaders object. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the column header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized column header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -10935,22 +11409,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -10964,7 +11438,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -11003,16 +11480,20 @@ def __ne__(self, other: 'TableColumnHeaders') -> bool: return not self == other -class TableElementLocation(): +class TableElementLocation: """ The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr int begin: The element's `begin` index. - :attr int end: The element's `end` index. + :param int begin: The element's `begin` index. + :param int end: The element's `end` index. """ - def __init__(self, begin: int, end: int) -> None: + def __init__( + self, + begin: int, + end: int, + ) -> None: """ Initialize a TableElementLocation object. @@ -11026,14 +11507,14 @@ def __init__(self, begin: int, end: int) -> None: def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in TableElementLocation JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in TableElementLocation JSON' @@ -11073,43 +11554,45 @@ def __ne__(self, other: 'TableElementLocation') -> bool: return not self == other -class TableHeaders(): +class TableHeaders: """ The contents of the current table's header. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr dict location: (optional) The location of the table header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of the cell from the input + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The textual contents of the cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: dict = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableHeaders object. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the table header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of the cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's @@ -11133,20 +11616,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -11160,7 +11643,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -11196,19 +11682,21 @@ def __ne__(self, other: 'TableHeaders') -> bool: return not self == other -class TableKeyValuePairs(): +class TableKeyValuePairs: """ Key-value pairs detected across cell boundaries. - :attr TableCellKey key: (optional) A key in a key-value pair. - :attr List[TableCellValues] value: (optional) A list of values in a key-value + :param TableCellKey key: (optional) A key in a key-value pair. + :param List[TableCellValues] value: (optional) A list of values in a key-value pair. """ - def __init__(self, - *, - key: 'TableCellKey' = None, - value: List['TableCellValues'] = None) -> None: + def __init__( + self, + *, + key: Optional['TableCellKey'] = None, + value: Optional[List['TableCellValues']] = None, + ) -> None: """ Initialize a TableKeyValuePairs object. @@ -11223,12 +11711,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = TableCellKey.from_dict(_dict.get('key')) - if 'value' in _dict: - args['value'] = [ - TableCellValues.from_dict(v) for v in _dict.get('value') - ] + if (key := _dict.get('key')) is not None: + args['key'] = TableCellKey.from_dict(key) + if (value := _dict.get('value')) is not None: + args['value'] = [TableCellValues.from_dict(v) for v in value] return cls(**args) @classmethod @@ -11273,48 +11759,50 @@ def __ne__(self, other: 'TableKeyValuePairs') -> bool: return not self == other -class TableResultTable(): +class TableResultTable: """ Full table object retrieved from Table Understanding Enrichment. - :attr TableElementLocation location: (optional) The numeric location of the + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of the current table from the + :param str text: (optional) The textual contents of the current table from the input document without associated markup content. - :attr TableTextLocation section_title: (optional) Text and associated location + :param TableTextLocation section_title: (optional) Text and associated location within a table. - :attr TableTextLocation title: (optional) Text and associated location within a + :param TableTextLocation title: (optional) Text and associated location within a table. - :attr List[TableHeaders] table_headers: (optional) An array of table-level cells - that apply as headers to all the other cells in the current table. - :attr List[TableRowHeaders] row_headers: (optional) An array of row-level cells, - each applicable as a header to other cells in the same row as itself, of the - current table. - :attr List[TableColumnHeaders] column_headers: (optional) An array of + :param List[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param List[TableRowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as itself, of + the current table. + :param List[TableColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr List[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value - pairs identified in the current table. - :attr List[TableBodyCells] body_cells: (optional) An array of cells that are + :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of + key-value pairs identified in the current table. + :param List[TableBodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :attr List[TableTextLocation] contexts: (optional) An array of lists of textual + :param List[TableTextLocation] contexts: (optional) An array of lists of textual entries across the document related to the current table being parsed. """ - def __init__(self, - *, - location: 'TableElementLocation' = None, - text: str = None, - section_title: 'TableTextLocation' = None, - title: 'TableTextLocation' = None, - table_headers: List['TableHeaders'] = None, - row_headers: List['TableRowHeaders'] = None, - column_headers: List['TableColumnHeaders'] = None, - key_value_pairs: List['TableKeyValuePairs'] = None, - body_cells: List['TableBodyCells'] = None, - contexts: List['TableTextLocation'] = None) -> None: + def __init__( + self, + *, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + section_title: Optional['TableTextLocation'] = None, + title: Optional['TableTextLocation'] = None, + table_headers: Optional[List['TableHeaders']] = None, + row_headers: Optional[List['TableRowHeaders']] = None, + column_headers: Optional[List['TableColumnHeaders']] = None, + key_value_pairs: Optional[List['TableKeyValuePairs']] = None, + body_cells: Optional[List['TableBodyCells']] = None, + contexts: Optional[List['TableTextLocation']] = None, + ) -> None: """ Initialize a TableResultTable object. @@ -11359,41 +11847,37 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableResultTable': """Initialize a TableResultTable object from a json dictionary.""" args = {} - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'section_title' in _dict: - args['section_title'] = TableTextLocation.from_dict( - _dict.get('section_title')) - if 'title' in _dict: - args['title'] = TableTextLocation.from_dict(_dict.get('title')) - if 'table_headers' in _dict: + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (section_title := _dict.get('section_title')) is not None: + args['section_title'] = TableTextLocation.from_dict(section_title) + if (title := _dict.get('title')) is not None: + args['title'] = TableTextLocation.from_dict(title) + if (table_headers := _dict.get('table_headers')) is not None: args['table_headers'] = [ - TableHeaders.from_dict(v) for v in _dict.get('table_headers') + TableHeaders.from_dict(v) for v in table_headers ] - if 'row_headers' in _dict: + if (row_headers := _dict.get('row_headers')) is not None: args['row_headers'] = [ - TableRowHeaders.from_dict(v) for v in _dict.get('row_headers') + TableRowHeaders.from_dict(v) for v in row_headers ] - if 'column_headers' in _dict: + if (column_headers := _dict.get('column_headers')) is not None: args['column_headers'] = [ - TableColumnHeaders.from_dict(v) - for v in _dict.get('column_headers') + TableColumnHeaders.from_dict(v) for v in column_headers ] - if 'key_value_pairs' in _dict: + if (key_value_pairs := _dict.get('key_value_pairs')) is not None: args['key_value_pairs'] = [ - TableKeyValuePairs.from_dict(v) - for v in _dict.get('key_value_pairs') + TableKeyValuePairs.from_dict(v) for v in key_value_pairs ] - if 'body_cells' in _dict: + if (body_cells := _dict.get('body_cells')) is not None: args['body_cells'] = [ - TableBodyCells.from_dict(v) for v in _dict.get('body_cells') + TableBodyCells.from_dict(v) for v in body_cells ] - if 'contexts' in _dict: + if (contexts := _dict.get('contexts')) is not None: args['contexts'] = [ - TableTextLocation.from_dict(v) for v in _dict.get('contexts') + TableTextLocation.from_dict(v) for v in contexts ] return cls(**args) @@ -11492,208 +11976,40 @@ def __ne__(self, other: 'TableResultTable') -> bool: return not self == other -class TableRowHeaderIds(): - """ - An array of values, each being the `id` value of a row header that is applicable to - this body cell. - - :attr str id: (optional) The `id` values of a row header. - """ - - def __init__(self, *, id: str = None) -> None: - """ - Initialize a TableRowHeaderIds object. - - :param str id: (optional) The `id` values of a row header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': - """Initialize a TableRowHeaderIds object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderIds object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderIds') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableRowHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderTexts(): - """ - An array of values, each being the `text` value of a row header that is applicable to - this body cell. - - :attr str text: (optional) The `text` value of a row header. - """ - - def __init__(self, *, text: str = None) -> None: - """ - Initialize a TableRowHeaderTexts object. - - :param str text: (optional) The `text` value of a row header. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': - """Initialize a TableRowHeaderTexts object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTexts object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderTexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderTexts') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableRowHeaderTexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderTextsNormalized(): - """ - If you provide customization input, the normalized version of the row header texts - according to the customization; otherwise, the same value as `row_header_texts`. - - :attr str text_normalized: (optional) The normalized version of a row header - text. - """ - - def __init__(self, *, text_normalized: str = None) -> None: - """ - Initialize a TableRowHeaderTextsNormalized object. - - :param str text_normalized: (optional) The normalized version of a row - header text. - """ - self.text_normalized = text_normalized - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': - """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" - args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderTextsNormalized object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderTextsNormalized') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableRowHeaderTextsNormalized') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaders(): +class TableRowHeaders: """ Row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param str text_normalized: (optional) Normalized row header text. + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableRowHeaders object. @@ -11704,9 +12020,7 @@ def __init__(self, labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized row header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -11729,23 +12043,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -11801,20 +12114,22 @@ def __ne__(self, other: 'TableRowHeaders') -> bool: return not self == other -class TableTextLocation(): +class TableTextLocation: """ Text and associated location within a table. - :attr str text: (optional) The text retrieved. - :attr TableElementLocation location: (optional) The numeric location of the + :param str text: (optional) The text retrieved. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ - def __init__(self, - *, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ Initialize a TableTextLocation object. @@ -11830,11 +12145,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod @@ -11873,25 +12187,29 @@ def __ne__(self, other: 'TableTextLocation') -> bool: return not self == other -class TrainingExample(): +class TrainingExample: """ Object that contains example response details for a training query. - :attr str document_id: The document ID associated with this training example. - :attr str collection_id: The collection ID associated with this training + :param str document_id: The document ID associated with this training example. + :param str collection_id: The collection ID associated with this training example. - :attr int relevance: The relevance of the training example. - :attr datetime created: (optional) The date and time the example was created. - :attr datetime updated: (optional) The date and time the example was updated. + :param int relevance: The relevance score of the training example. Scores range + from `0` to `100`. Zero means not relevant. The higher the number, the more + relevant the example. + :param datetime created: (optional) The date and time the example was created. + :param datetime updated: (optional) The date and time the example was updated. """ - def __init__(self, - document_id: str, - collection_id: str, - relevance: int, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + document_id: str, + collection_id: str, + relevance: int, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingExample object. @@ -11899,7 +12217,9 @@ def __init__(self, example. :param str collection_id: The collection ID associated with this training example. - :param int relevance: The relevance of the training example. + :param int relevance: The relevance score of the training example. Scores + range from `0` to `100`. Zero means not relevant. The higher the number, + the more relevant the example. """ self.document_id = document_id self.collection_id = collection_id @@ -11911,28 +12231,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in TrainingExample JSON' ) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in TrainingExample JSON' ) - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance else: raise ValueError( 'Required property \'relevance\' not present in TrainingExample JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -11974,28 +12294,34 @@ def __ne__(self, other: 'TrainingExample') -> bool: return not self == other -class TrainingQuery(): +class TrainingQuery: """ Object that contains training query details. - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: The natural text query that is used as the + :param str query_id: (optional) The query ID associated with the training query. + :param str natural_language_query: The natural text query that is used as the training query. - :attr str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :attr datetime created: (optional) The date and time the query was created. - :attr datetime updated: (optional) The date and time the query was updated. - :attr List[TrainingExample] examples: Array of training examples. - """ - - def __init__(self, - natural_language_query: str, - examples: List['TrainingExample'], - *, - query_id: str = None, - filter: str = None, - created: datetime = None, - updated: datetime = None) -> None: + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. Only specify a filter if the documents + that you consider to be most relevant are not included in the top 100 results + when you submit test queries. If you specify a filter during training, apply the + same filter to queries that are submitted at runtime for optimal ranking + results. + :param datetime created: (optional) The date and time the query was created. + :param datetime updated: (optional) The date and time the query was updated. + :param List[TrainingExample] examples: Array of training examples. + """ + + def __init__( + self, + natural_language_query: str, + examples: List['TrainingExample'], + *, + query_id: Optional[str] = None, + filter: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingQuery object. @@ -12003,7 +12329,11 @@ def __init__(self, the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -12016,24 +12346,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query else: raise ValueError( 'Required property \'natural_language_query\' not present in TrainingQuery JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in TrainingQuery JSON' @@ -12088,16 +12417,20 @@ def __ne__(self, other: 'TrainingQuery') -> bool: return not self == other -class TrainingQuerySet(): +class TrainingQuerySet: """ Object specifying the training queries contained in the identified training set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. At + :param List[TrainingQuery] queries: (optional) Array of training queries. At least 50 queries are required for training to begin. A maximum of 10,000 queries are returned. """ - def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: + def __init__( + self, + *, + queries: Optional[List['TrainingQuery']] = None, + ) -> None: """ Initialize a TrainingQuerySet object. @@ -12111,10 +12444,8 @@ def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': """Initialize a TrainingQuerySet object from a json dictionary.""" args = {} - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(v) for v in _dict.get('queries') - ] + if (queries := _dict.get('queries')) is not None: + args['queries'] = [TrainingQuery.from_dict(v) for v in queries] return cls(**args) @classmethod @@ -12154,16 +12485,21 @@ def __ne__(self, other: 'TrainingQuerySet') -> bool: return not self == other -class UpdateDocumentClassifier(): +class UpdateDocumentClassifier: """ An object that contains a new name or description for a document classifier, updated training data, or new or updated test data. - :attr str name: (optional) A new name for the classifier. - :attr str description: (optional) A new description for the classifier. + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. """ - def __init__(self, *, name: str = None, description: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a UpdateDocumentClassifier object. @@ -12177,10 +12513,10 @@ def __init__(self, *, name: str = None, description: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'UpdateDocumentClassifier': """Initialize a UpdateDocumentClassifier object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -12216,22 +12552,96 @@ def __ne__(self, other: 'UpdateDocumentClassifier') -> bool: return not self == other +class WebhookHeader: + """ + An array of headers to pass with the HTTP request. Optional when `type` is `webhook`. + Not valid when creating any other type of enrichment. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + + def __init__( + self, + name: str, + value: str, + ) -> None: + """ + Initialize a WebhookHeader object. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + self.name = name + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': + """Initialize a WebhookHeader object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in WebhookHeader JSON') + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in WebhookHeader JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WebhookHeader object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WebhookHeader') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WebhookHeader') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. - :attr str type: (optional) Specifies the calculation type, such as 'average`, + :param str type: (optional) Specifies the calculation type, such as 'average`, `max`, `min`, `sum`, or `unique_count`. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ - def __init__(self, - field: str, - *, - type: str = None, - value: float = None) -> None: + def __init__( + self, + field: str, + *, + type: Optional[str] = None, + value: Optional[float] = None, + ) -> None: """ Initialize a QueryAggregationQueryCalculationAggregation object. @@ -12250,16 +12660,16 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryCalculationAggregation': """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryCalculationAggregation JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod @@ -12303,19 +12713,21 @@ class QueryAggregationQueryFilterAggregation(QueryAggregation): """ A modifier that narrows the document set of the subaggregations it precedes. - :attr str type: (optional) Specifies that the aggregation type is `filter`. - :attr str match: The filter that is written in Discovery Query Language syntax + :param str type: (optional) Specifies that the aggregation type is `filter`. + :param str match: The filter that is written in Discovery Query Language syntax and is applied to the documents before subaggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[dict] aggregations: (optional) An array of subaggregations. + :param int matching_results: Number of documents that match the filter. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - match: str, - matching_results: int, - *, - type: str = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + match: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryAggregationQueryFilterAggregation object. @@ -12336,22 +12748,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryFilterAggregation': """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'match' in _dict: - args['match'] = _dict.get('match') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (match := _dict.get('match')) is not None: + args['match'] = match else: raise ValueError( 'Required property \'match\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -12396,15 +12808,17 @@ class QueryAggregationQueryGroupByAggregation(QueryAggregation): """ Separates document results into groups that meet the conditions you specify. - :attr str type: (optional) Specifies that the aggregation type is `group_by`. - :attr List[QueryGroupByAggregationResult] results: (optional) An array of + :param str type: (optional) Specifies that the aggregation type is `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of results. """ - def __init__(self, - *, - type: str = None, - results: List['QueryGroupByAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + results: Optional[List['QueryGroupByAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryGroupByAggregation object. @@ -12422,12 +12836,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryGroupByAggregation': """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryGroupByAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryGroupByAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12475,23 +12888,24 @@ class QueryAggregationQueryHistogramAggregation(QueryAggregation): Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. - :attr str type: (optional) Specifies that the aggregation type is `histogram`. - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier that can optionally be specified in the + :param str type: (optional) Specifies that the aggregation type is `histogram`. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split into. + :param str name: (optional) Identifier that can optionally be specified in the query request of this aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ def __init__( - self, - field: str, - interval: int, - *, - type: str = None, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: + self, + field: str, + interval: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryHistogramAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryHistogramAggregation object. @@ -12517,26 +12931,25 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryHistogramAggregation': """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12593,20 +13006,22 @@ class QueryAggregationQueryNestedAggregation(QueryAggregation): precedes. Subsequent aggregations are applied to nested documents from the specified field. - :attr str type: (optional) Specifies that the aggregation type is `nested`. - :attr str path: The path to the document field to scope subsequent aggregations + :param str type: (optional) Specifies that the aggregation type is `nested`. + :param str path: The path to the document field to scope subsequent aggregations to. - :attr int matching_results: Number of nested documents found in the specified + :param int matching_results: Number of nested documents found in the specified field. - :attr List[dict] aggregations: (optional) An array of subaggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - path: str, - matching_results: int, - *, - type: str = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + path: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryAggregationQueryNestedAggregation object. @@ -12628,22 +13043,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryNestedAggregation': """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'path' in _dict: - args['path'] = _dict.get('path') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (path := _dict.get('path')) is not None: + args['path'] = path else: raise ValueError( 'Required property \'path\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -12689,29 +13104,31 @@ class QueryAggregationQueryPairAggregation(QueryAggregation): Calculates relevancy values using combinations of document sets from results of the specified pair of aggregations. - :attr str type: (optional) Specifies that the aggregation type is `pair`. - :attr str first: (optional) Specifies the first aggregation in the pair. The + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` aggregation type. - :attr str second: (optional) Specifies the second aggregation in the pair. The + :param str second: (optional) Specifies the second aggregation in the pair. The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` aggregation type. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryPairAggregationResult] results: (optional) An array of + :param List[QueryPairAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - first: str = None, - second: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryPairAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + first: Optional[str] = None, + second: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryPairAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryPairAggregation object. @@ -12741,22 +13158,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryPairAggregation': """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'first' in _dict: - args['first'] = _dict.get('first') - if 'second' in _dict: - args['second'] = _dict.get('second') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (first := _dict.get('first')) is not None: + args['first'] = first + if (second := _dict.get('second')) is not None: + args['second'] = second + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryPairAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryPairAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12815,23 +13233,25 @@ class QueryAggregationQueryTermAggregation(QueryAggregation): """ Returns results from the field that is specified. - :attr str type: (optional) Specifies that the aggregation type is `term`. - :attr str field: (optional) The field in the document where the values come + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values come from. - :attr int count: (optional) The number of results returned. Not returned if + :param int count: (optional) The number of results returned. Not returned if `relevancy:true` is specified in the request. - :attr str name: (optional) Identifier specified in the query request of this + :param str name: (optional) Identifier specified in the query request of this aggregation. Not returned if `relevancy:true` is specified in the request. - :attr List[QueryTermAggregationResult] results: (optional) An array of results. + :param List[QueryTermAggregationResult] results: (optional) An array of results. """ - def __init__(self, - *, - type: str = None, - field: str = None, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + field: Optional[str] = None, + count: Optional[int] = None, + name: Optional[str] = None, + results: Optional[List['QueryTermAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTermAggregation object. @@ -12857,18 +13277,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTermAggregation': """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field + if (count := _dict.get('count')) is not None: + args['count'] = count + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTermAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTermAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12921,24 +13340,25 @@ class QueryAggregationQueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. - :attr str type: (optional) Specifies that the aggregation type is `timeslice`. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, + :param str type: (optional) Specifies that the aggregation type is `timeslice`. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier that can optionally be specified in the + :param str name: (optional) Identifier that can optionally be specified in the query request of this aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( - self, - field: str, - interval: str, - *, - type: str = None, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: + self, + field: str, + interval: str, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryTimesliceAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTimesliceAggregation object. @@ -12964,26 +13384,25 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTimesliceAggregation': """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -13038,20 +13457,22 @@ class QueryAggregationQueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. - :attr str type: (optional) Specifies that the aggregation type is `top_hits`. - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this + :param str type: (optional) Specifies that the aggregation type is `top_hits`. + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) A query response that + :param QueryTopHitsAggregationResult hits: (optional) A query response that contains the matching documents for the preceding aggregations. """ - def __init__(self, - size: int, - *, - type: str = None, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: + def __init__( + self, + size: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + hits: Optional['QueryTopHitsAggregationResult'] = None, + ) -> None: """ Initialize a QueryAggregationQueryTopHitsAggregation object. @@ -13074,19 +13495,18 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopHitsAggregation': """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'size' in _dict: - args['size'] = _dict.get('size') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (size := _dict.get('size')) is not None: + args['size'] = size else: raise ValueError( 'Required property \'size\' not present in QueryAggregationQueryTopHitsAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (hits := _dict.get('hits')) is not None: + args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) return cls(**args) @classmethod @@ -13136,27 +13556,29 @@ class QueryAggregationQueryTopicAggregation(QueryAggregation): previous time periods. It calculates an index by using the averages of frequency counts of other facet values for the given time period. - :attr str type: (optional) Specifies that the aggregation type is `topic`. - :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for the facet that you want to analyze. - :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + :param str time_segments: (optional) Specifies the `timeslice` aggregation that defines the time segments. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryTopicAggregationResult] results: (optional) An array of + :param List[QueryTopicAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - facet: str = None, - time_segments: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryTopicAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTopicAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTopicAggregation object. @@ -13184,22 +13606,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopicAggregation': """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'facet' in _dict: - args['facet'] = _dict.get('facet') - if 'time_segments' in _dict: - args['time_segments'] = _dict.get('time_segments') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTopicAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTopicAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -13259,27 +13682,29 @@ class QueryAggregationQueryTrendAggregation(QueryAggregation): Detects sharp and unexpected changes in the frequency of a facet or facet value over time based on the past history of frequency changes of the facet value. - :attr str type: (optional) Specifies that the aggregation type is `trend`. - :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for the facet that you want to analyze. - :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + :param str time_segments: (optional) Specifies the `timeslice` aggregation that defines the time segments. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryTrendAggregationResult] results: (optional) An array of + :param List[QueryTrendAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - facet: str = None, - time_segments: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryTrendAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTrendAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTrendAggregation object. @@ -13307,22 +13732,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTrendAggregation': """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'facet' in _dict: - args['facet'] = _dict.get('facet') - if 'time_segments' in _dict: - args['time_segments'] = _dict.get('time_segments') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTrendAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTrendAggregationResult.from_dict(v) for v in results ] return cls(**args) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 448e78ec..ea5be9f6 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,8 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ +IBM® is announcing the deprecation of the Watson® Language Translator service for +IBM Cloud® in all regions. As of 10 June 2023, the Language Translator tile will be +removed from the IBM Cloud Platform for new customers; only existing customers will be +able to access the product. As of 10 June 2024, the service will reach its End of Support +date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be +available to any customers.{: deprecated} IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the @@ -29,7 +35,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List, TextIO, Union +from typing import BinaryIO, Dict, List, Optional, TextIO, Union import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -69,6 +75,13 @@ def __init__( if version is None: raise ValueError('version must be provided') + print(""" + On 10 June 2023, IBM announced the deprecation of the Natural Language Translator service. + The service will no longer be available from 8 August 2022. As of 10 June 2024, the service will reach its End of Support + date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be + available to any customers. + """) + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, @@ -81,7 +94,10 @@ def __init__( # Languages ######################### - def list_languages(self, **kwargs) -> DetailedResponse: + def list_languages( + self, + **kwargs, + ) -> DetailedResponse: """ List supported languages. @@ -98,9 +114,11 @@ def list_languages(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_languages') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_languages', + ) headers.update(sdk_headers) params = { @@ -113,10 +131,12 @@ def list_languages(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -125,13 +145,15 @@ def list_languages(self, **kwargs) -> DetailedResponse: # Translation ######################### - def translate(self, - text: List[str], - *, - model_id: str = None, - source: str = None, - target: str = None, - **kwargs) -> DetailedResponse: + def translate( + self, + text: List[str], + *, + model_id: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Translate. @@ -166,9 +188,11 @@ def translate(self, if text is None: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate', + ) headers.update(sdk_headers) params = { @@ -191,11 +215,13 @@ def translate(self, headers['Accept'] = 'application/json' url = '/v3/translate' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -204,7 +230,10 @@ def translate(self, # Identification ######################### - def list_identifiable_languages(self, **kwargs) -> DetailedResponse: + def list_identifiable_languages( + self, + **kwargs, + ) -> DetailedResponse: """ List identifiable languages. @@ -220,7 +249,8 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', - operation_id='list_identifiable_languages') + operation_id='list_identifiable_languages', + ) headers.update(sdk_headers) params = { @@ -233,15 +263,21 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/identifiable_languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: + def identify( + self, + text: Union[str, TextIO], + **kwargs, + ) -> DetailedResponse: """ Identify language. @@ -256,9 +292,11 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='identify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='identify', + ) headers.update(sdk_headers) params = { @@ -274,11 +312,13 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/identify' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -287,12 +327,14 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: # Models ######################### - def list_models(self, - *, - source: str = None, - target: str = None, - default: bool = None, - **kwargs) -> DetailedResponse: + def list_models( + self, + *, + source: Optional[str] = None, + target: Optional[str] = None, + default: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -313,9 +355,11 @@ def list_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_models', + ) headers.update(sdk_headers) params = { @@ -331,23 +375,27 @@ def list_models(self, headers['Accept'] = 'application/json' url = '/v3/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_model(self, - base_model_id: str, - *, - forced_glossary: BinaryIO = None, - forced_glossary_content_type: str = None, - parallel_corpus: BinaryIO = None, - parallel_corpus_content_type: str = None, - name: str = None, - **kwargs) -> DetailedResponse: + def create_model( + self, + base_model_id: str, + *, + forced_glossary: Optional[BinaryIO] = None, + forced_glossary_content_type: Optional[str] = None, + parallel_corpus: Optional[BinaryIO] = None, + parallel_corpus_content_type: Optional[str] = None, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create model. @@ -451,9 +499,11 @@ def create_model(self, if not base_model_id: raise ValueError('base_model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='create_model', + ) headers.update(sdk_headers) params = { @@ -480,16 +530,22 @@ def create_model(self, headers['Accept'] = 'application/json' url = '/v3/models' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: + def delete_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete model. @@ -504,9 +560,11 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_model', + ) headers.update(sdk_headers) params = { @@ -522,15 +580,21 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get model details. @@ -547,9 +611,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_model', + ) headers.update(sdk_headers) params = { @@ -565,10 +631,12 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -577,7 +645,10 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: # Document translation ######################### - def list_documents(self, **kwargs) -> DetailedResponse: + def list_documents( + self, + **kwargs, + ) -> DetailedResponse: """ List documents. @@ -589,9 +660,11 @@ def list_documents(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_documents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_documents', + ) headers.update(sdk_headers) params = { @@ -604,24 +677,28 @@ def list_documents(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/documents' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def translate_document(self, - file: BinaryIO, - *, - filename: str = None, - file_content_type: str = None, - model_id: str = None, - source: str = None, - target: str = None, - document_id: str = None, - **kwargs) -> DetailedResponse: + def translate_document( + self, + file: BinaryIO, + *, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + model_id: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + document_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Translate document. @@ -685,9 +762,11 @@ def translate_document(self, if file is None: raise ValueError('file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate_document', + ) headers.update(sdk_headers) params = { @@ -716,17 +795,22 @@ def translate_document(self, headers['Accept'] = 'application/json' url = '/v3/documents' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_status(self, document_id: str, - **kwargs) -> DetailedResponse: + def get_document_status( + self, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document status. @@ -741,9 +825,11 @@ def get_document_status(self, document_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_document_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_document_status', + ) headers.update(sdk_headers) params = { @@ -759,15 +845,21 @@ def get_document_status(self, document_id: str, path_param_values = self.encode_path_vars(document_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: + def delete_document( + self, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete document. @@ -782,9 +874,11 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -799,19 +893,23 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(document_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_translated_document(self, - document_id: str, - *, - accept: str = None, - **kwargs) -> DetailedResponse: + def get_translated_document( + self, + document_id: str, + *, + accept: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get translated document. @@ -843,9 +941,11 @@ def get_translated_document(self, headers = { 'Accept': accept, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_translated_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_translated_document', + ) headers.update(sdk_headers) params = { @@ -861,10 +961,12 @@ def get_translated_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}/translated_document'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -879,6 +981,7 @@ class ForcedGlossaryContentType(str, Enum): """ The content type of forced_glossary. """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' APPLICATION_XLIFF_XML = 'application/xliff+xml' TEXT_CSV = 'text/csv' @@ -890,6 +993,7 @@ class ParallelCorpusContentType(str, Enum): """ The content type of parallel_corpus. """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' APPLICATION_XLIFF_XML = 'application/xliff+xml' TEXT_CSV = 'text/csv' @@ -907,6 +1011,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' APPLICATION_MSWORD = 'application/msword' APPLICATION_OCTET_STREAM = 'application/octet-stream' @@ -957,6 +1062,7 @@ class Accept(str, Enum): character encoding can be specified by including a `charset` parameter. For example, 'text/html;charset=utf-8'. """ + APPLICATION_POWERPOINT = 'application/powerpoint' APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' APPLICATION_X_RTF = 'application/x-rtf' @@ -986,14 +1092,17 @@ class Accept(str, Enum): ############################################################################## -class DeleteModelResult(): +class DeleteModelResult: """ DeleteModelResult. - :attr str status: "OK" indicates that the model was successfully deleted. + :param str status: "OK" indicates that the model was successfully deleted. """ - def __init__(self, status: str) -> None: + def __init__( + self, + status: str, + ) -> None: """ Initialize a DeleteModelResult object. @@ -1005,8 +1114,8 @@ def __init__(self, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': """Initialize a DeleteModelResult object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteModelResult JSON' @@ -1044,15 +1153,18 @@ def __ne__(self, other: 'DeleteModelResult') -> bool: return not self == other -class DocumentList(): +class DocumentList: """ DocumentList. - :attr List[DocumentStatus] documents: An array of all previously submitted + :param List[DocumentStatus] documents: An array of all previously submitted documents. """ - def __init__(self, documents: List['DocumentStatus']) -> None: + def __init__( + self, + documents: List['DocumentStatus'], + ) -> None: """ Initialize a DocumentList object. @@ -1065,10 +1177,8 @@ def __init__(self, documents: List['DocumentStatus']) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentList': """Initialize a DocumentList object from a json dictionary.""" args = {} - if 'documents' in _dict: - args['documents'] = [ - DocumentStatus.from_dict(v) for v in _dict.get('documents') - ] + if (documents := _dict.get('documents')) is not None: + args['documents'] = [DocumentStatus.from_dict(v) for v in documents] else: raise ValueError( 'Required property \'documents\' not present in DocumentList JSON' @@ -1112,49 +1222,51 @@ def __ne__(self, other: 'DocumentList') -> bool: return not self == other -class DocumentStatus(): +class DocumentStatus: """ Document information, including translation status. - :attr str document_id: System generated ID identifying a document being + :param str document_id: System generated ID identifying a document being translated using one specific translation model. - :attr str filename: filename from the submission (if it was missing in the + :param str filename: filename from the submission (if it was missing in the multipart-form, 'noname.' is used. - :attr str status: The status of the translation job associated with a submitted + :param str status: The status of the translation job associated with a submitted document. - :attr str model_id: A globally unique string that identifies the underlying + :param str model_id: A globally unique string that identifies the underlying model that is used for translation. - :attr str base_model_id: (optional) Model ID of the base model that was used to + :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be absent or an empty string. - :attr str source: Translation source language code. - :attr float detected_language_confidence: (optional) A score between 0 and 1 + :param str source: Translation source language code. + :param float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. - :attr str target: Translation target language code. - :attr datetime created: The time when the document was submitted. - :attr datetime completed: (optional) The time when the translation completed. - :attr int word_count: (optional) An estimate of the number of words in the + :param str target: Translation target language code. + :param datetime created: The time when the document was submitted. + :param datetime completed: (optional) The time when the translation completed. + :param int word_count: (optional) An estimate of the number of words in the source document. Returned only if `status` is `available`. - :attr int character_count: (optional) The number of characters in the source + :param int character_count: (optional) The number of characters in the source document, present only if status=available. """ - def __init__(self, - document_id: str, - filename: str, - status: str, - model_id: str, - source: str, - target: str, - created: datetime, - *, - base_model_id: str = None, - detected_language_confidence: float = None, - completed: datetime = None, - word_count: int = None, - character_count: int = None) -> None: + def __init__( + self, + document_id: str, + filename: str, + status: str, + model_id: str, + source: str, + target: str, + created: datetime, + *, + base_model_id: Optional[str] = None, + detected_language_confidence: Optional[float] = None, + completed: Optional[datetime] = None, + word_count: Optional[int] = None, + character_count: Optional[int] = None, + ) -> None: """ Initialize a DocumentStatus object. @@ -1200,59 +1312,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in DocumentStatus JSON' ) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename else: raise ValueError( 'Required property \'filename\' not present in DocumentStatus JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DocumentStatus JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in DocumentStatus JSON' ) - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'source' in _dict: - args['source'] = _dict.get('source') + if (base_model_id := _dict.get('base_model_id')) is not None: + args['base_model_id'] = base_model_id + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DocumentStatus JSON' ) - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'target' in _dict: - args['target'] = _dict.get('target') + if (detected_language_confidence := + _dict.get('detected_language_confidence')) is not None: + args['detected_language_confidence'] = detected_language_confidence + if (target := _dict.get('target')) is not None: + args['target'] = target else: raise ValueError( 'Required property \'target\' not present in DocumentStatus JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in DocumentStatus JSON' ) - if 'completed' in _dict: - args['completed'] = string_to_datetime(_dict.get('completed')) - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') + if (completed := _dict.get('completed')) is not None: + args['completed'] = string_to_datetime(completed) + if (word_count := _dict.get('word_count')) is not None: + args['word_count'] = word_count + if (character_count := _dict.get('character_count')) is not None: + args['character_count'] = character_count return cls(**args) @classmethod @@ -1314,20 +1426,25 @@ class StatusEnum(str, Enum): """ The status of the translation job associated with a submitted document. """ + PROCESSING = 'processing' AVAILABLE = 'available' FAILED = 'failed' -class IdentifiableLanguage(): +class IdentifiableLanguage: """ IdentifiableLanguage. - :attr str language: The language code for an identifiable language. - :attr str name: The name of the identifiable language. + :param str language: The language code for an identifiable language. + :param str name: The name of the identifiable language. """ - def __init__(self, language: str, name: str) -> None: + def __init__( + self, + language: str, + name: str, + ) -> None: """ Initialize a IdentifiableLanguage object. @@ -1341,14 +1458,14 @@ def __init__(self, language: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in IdentifiableLanguage JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in IdentifiableLanguage JSON' @@ -1388,15 +1505,18 @@ def __ne__(self, other: 'IdentifiableLanguage') -> bool: return not self == other -class IdentifiableLanguages(): +class IdentifiableLanguages: """ IdentifiableLanguages. - :attr List[IdentifiableLanguage] languages: A list of all languages that the + :param List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ - def __init__(self, languages: List['IdentifiableLanguage']) -> None: + def __init__( + self, + languages: List['IdentifiableLanguage'], + ) -> None: """ Initialize a IdentifiableLanguages object. @@ -1409,10 +1529,9 @@ def __init__(self, languages: List['IdentifiableLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} - if 'languages' in _dict: + if (languages := _dict.get('languages')) is not None: args['languages'] = [ - IdentifiableLanguage.from_dict(v) - for v in _dict.get('languages') + IdentifiableLanguage.from_dict(v) for v in languages ] else: raise ValueError( @@ -1457,15 +1576,19 @@ def __ne__(self, other: 'IdentifiableLanguages') -> bool: return not self == other -class IdentifiedLanguage(): +class IdentifiedLanguage: """ IdentifiedLanguage. - :attr str language: The language code for an identified language. - :attr float confidence: The confidence score for the identified language. + :param str language: The language code for an identified language. + :param float confidence: The confidence score for the identified language. """ - def __init__(self, language: str, confidence: float) -> None: + def __init__( + self, + language: str, + confidence: float, + ) -> None: """ Initialize a IdentifiedLanguage object. @@ -1479,14 +1602,14 @@ def __init__(self, language: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in IdentifiedLanguage JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in IdentifiedLanguage JSON' @@ -1526,15 +1649,18 @@ def __ne__(self, other: 'IdentifiedLanguage') -> bool: return not self == other -class IdentifiedLanguages(): +class IdentifiedLanguages: """ IdentifiedLanguages. - :attr List[IdentifiedLanguage] languages: A ranking of identified languages with - confidence scores. + :param List[IdentifiedLanguage] languages: A ranking of identified languages + with confidence scores. """ - def __init__(self, languages: List['IdentifiedLanguage']) -> None: + def __init__( + self, + languages: List['IdentifiedLanguage'], + ) -> None: """ Initialize a IdentifiedLanguages object. @@ -1547,9 +1673,9 @@ def __init__(self, languages: List['IdentifiedLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} - if 'languages' in _dict: + if (languages := _dict.get('languages')) is not None: args['languages'] = [ - IdentifiedLanguage.from_dict(v) for v in _dict.get('languages') + IdentifiedLanguage.from_dict(v) for v in languages ] else: raise ValueError( @@ -1594,45 +1720,47 @@ def __ne__(self, other: 'IdentifiedLanguages') -> bool: return not self == other -class Language(): +class Language: """ Response payload for languages. - :attr str language: (optional) The language code for the language (for example, + :param str language: (optional) The language code for the language (for example, `af`). - :attr str language_name: (optional) The name of the language in English (for + :param str language_name: (optional) The name of the language in English (for example, `Afrikaans`). - :attr str native_language_name: (optional) The native name of the language (for + :param str native_language_name: (optional) The native name of the language (for example, `Afrikaans`). - :attr str country_code: (optional) The country code for the language (for + :param str country_code: (optional) The country code for the language (for example, `ZA` for South Africa). - :attr bool words_separated: (optional) Indicates whether words of the language + :param bool words_separated: (optional) Indicates whether words of the language are separated by whitespace: `true` if the words are separated; `false` otherwise. - :attr str direction: (optional) Indicates the direction of the language: + :param str direction: (optional) Indicates the direction of the language: `right_to_left` or `left_to_right`. - :attr bool supported_as_source: (optional) Indicates whether the language can be - used as the source for translation: `true` if the language can be used as the + :param bool supported_as_source: (optional) Indicates whether the language can + be used as the source for translation: `true` if the language can be used as the source; `false` otherwise. - :attr bool supported_as_target: (optional) Indicates whether the language can be - used as the target for translation: `true` if the language can be used as the + :param bool supported_as_target: (optional) Indicates whether the language can + be used as the target for translation: `true` if the language can be used as the target; `false` otherwise. - :attr bool identifiable: (optional) Indicates whether the language supports + :param bool identifiable: (optional) Indicates whether the language supports automatic detection: `true` if the language can be detected automatically; `false` otherwise. """ - def __init__(self, - *, - language: str = None, - language_name: str = None, - native_language_name: str = None, - country_code: str = None, - words_separated: bool = None, - direction: str = None, - supported_as_source: bool = None, - supported_as_target: bool = None, - identifiable: bool = None) -> None: + def __init__( + self, + *, + language: Optional[str] = None, + language_name: Optional[str] = None, + native_language_name: Optional[str] = None, + country_code: Optional[str] = None, + words_separated: Optional[bool] = None, + direction: Optional[str] = None, + supported_as_source: Optional[bool] = None, + supported_as_target: Optional[bool] = None, + identifiable: Optional[bool] = None, + ) -> None: """ Initialize a Language object. @@ -1673,24 +1801,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Language': """Initialize a Language object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'language_name' in _dict: - args['language_name'] = _dict.get('language_name') - if 'native_language_name' in _dict: - args['native_language_name'] = _dict.get('native_language_name') - if 'country_code' in _dict: - args['country_code'] = _dict.get('country_code') - if 'words_separated' in _dict: - args['words_separated'] = _dict.get('words_separated') - if 'direction' in _dict: - args['direction'] = _dict.get('direction') - if 'supported_as_source' in _dict: - args['supported_as_source'] = _dict.get('supported_as_source') - if 'supported_as_target' in _dict: - args['supported_as_target'] = _dict.get('supported_as_target') - if 'identifiable' in _dict: - args['identifiable'] = _dict.get('identifiable') + if (language := _dict.get('language')) is not None: + args['language'] = language + if (language_name := _dict.get('language_name')) is not None: + args['language_name'] = language_name + if (native_language_name := + _dict.get('native_language_name')) is not None: + args['native_language_name'] = native_language_name + if (country_code := _dict.get('country_code')) is not None: + args['country_code'] = country_code + if (words_separated := _dict.get('words_separated')) is not None: + args['words_separated'] = words_separated + if (direction := _dict.get('direction')) is not None: + args['direction'] = direction + if (supported_as_source := + _dict.get('supported_as_source')) is not None: + args['supported_as_source'] = supported_as_source + if (supported_as_target := + _dict.get('supported_as_target')) is not None: + args['supported_as_target'] = supported_as_target + if (identifiable := _dict.get('identifiable')) is not None: + args['identifiable'] = identifiable return cls(**args) @classmethod @@ -1746,15 +1877,18 @@ def __ne__(self, other: 'Language') -> bool: return not self == other -class Languages(): +class Languages: """ The response type for listing supported languages. - :attr List[Language] languages: An array of supported languages with information - about each language. + :param List[Language] languages: An array of supported languages with + information about each language. """ - def __init__(self, languages: List['Language']) -> None: + def __init__( + self, + languages: List['Language'], + ) -> None: """ Initialize a Languages object. @@ -1767,10 +1901,8 @@ def __init__(self, languages: List['Language']) -> None: def from_dict(cls, _dict: Dict) -> 'Languages': """Initialize a Languages object from a json dictionary.""" args = {} - if 'languages' in _dict: - args['languages'] = [ - Language.from_dict(v) for v in _dict.get('languages') - ] + if (languages := _dict.get('languages')) is not None: + args['languages'] = [Language.from_dict(v) for v in languages] else: raise ValueError( 'Required property \'languages\' not present in Languages JSON') @@ -1813,14 +1945,17 @@ def __ne__(self, other: 'Languages') -> bool: return not self == other -class Translation(): +class Translation: """ Translation. - :attr str translation: Translation output in UTF-8. + :param str translation: Translation output in UTF-8. """ - def __init__(self, translation: str) -> None: + def __init__( + self, + translation: str, + ) -> None: """ Initialize a Translation object. @@ -1832,8 +1967,8 @@ def __init__(self, translation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' @@ -1871,43 +2006,45 @@ def __ne__(self, other: 'Translation') -> bool: return not self == other -class TranslationModel(): +class TranslationModel: """ Response payload for models. - :attr str model_id: A globally unique string that identifies the underlying + :param str model_id: A globally unique string that identifies the underlying model that is used for translation. - :attr str name: (optional) Optional name that can be specified when the model is - created. - :attr str source: (optional) Translation source language code. - :attr str target: (optional) Translation target language code. - :attr str base_model_id: (optional) Model ID of the base model that was used to + :param str name: (optional) Optional name that can be specified when the model + is created. + :param str source: (optional) Translation source language code. + :param str target: (optional) Translation target language code. + :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be an empty string. - :attr str domain: (optional) The domain of the translation model. - :attr bool customizable: (optional) Whether this model can be used as a base for - customization. Customized models are not further customizable, and some base + :param str domain: (optional) The domain of the translation model. + :param bool customizable: (optional) Whether this model can be used as a base + for customization. Customized models are not further customizable, and some base models are not customizable. - :attr bool default_model: (optional) Whether or not the model is a default + :param bool default_model: (optional) Whether or not the model is a default model. A default model is the model for a given language pair that will be used when that language pair is specified in the source and target parameters. - :attr str owner: (optional) Either an empty string, indicating the model is not + :param str owner: (optional) Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created the model. - :attr str status: (optional) Availability of a model. + :param str status: (optional) Availability of a model. """ - def __init__(self, - model_id: str, - *, - name: str = None, - source: str = None, - target: str = None, - base_model_id: str = None, - domain: str = None, - customizable: bool = None, - default_model: bool = None, - owner: str = None, - status: str = None) -> None: + def __init__( + self, + model_id: str, + *, + name: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + base_model_id: Optional[str] = None, + domain: Optional[str] = None, + customizable: Optional[bool] = None, + default_model: Optional[bool] = None, + owner: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a TranslationModel object. @@ -1948,30 +2085,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationModel': """Initialize a TranslationModel object from a json dictionary.""" args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in TranslationModel JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'target' in _dict: - args['target'] = _dict.get('target') - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') - if 'default_model' in _dict: - args['default_model'] = _dict.get('default_model') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (source := _dict.get('source')) is not None: + args['source'] = source + if (target := _dict.get('target')) is not None: + args['target'] = target + if (base_model_id := _dict.get('base_model_id')) is not None: + args['base_model_id'] = base_model_id + if (domain := _dict.get('domain')) is not None: + args['domain'] = domain + if (customizable := _dict.get('customizable')) is not None: + args['customizable'] = customizable + if (default_model := _dict.get('default_model')) is not None: + args['default_model'] = default_model + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -2026,6 +2163,7 @@ class StatusEnum(str, Enum): """ Availability of a model. """ + UPLOADING = 'uploading' UPLOADED = 'uploaded' DISPATCHING = 'dispatching' @@ -2038,14 +2176,17 @@ class StatusEnum(str, Enum): ERROR = 'error' -class TranslationModels(): +class TranslationModels: """ The response type for listing existing translation models. - :attr List[TranslationModel] models: An array of available models. + :param List[TranslationModel] models: An array of available models. """ - def __init__(self, models: List['TranslationModel']) -> None: + def __init__( + self, + models: List['TranslationModel'], + ) -> None: """ Initialize a TranslationModels object. @@ -2057,10 +2198,8 @@ def __init__(self, models: List['TranslationModel']) -> None: def from_dict(cls, _dict: Dict) -> 'TranslationModels': """Initialize a TranslationModels object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - TranslationModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [TranslationModel.from_dict(v) for v in models] else: raise ValueError( 'Required property \'models\' not present in TranslationModels JSON' @@ -2104,29 +2243,31 @@ def __ne__(self, other: 'TranslationModels') -> bool: return not self == other -class TranslationResult(): +class TranslationResult: """ TranslationResult. - :attr int word_count: An estimate of the number of words in the input text. - :attr int character_count: Number of characters in the input text. - :attr str detected_language: (optional) The language code of the source text if + :param int word_count: An estimate of the number of words in the input text. + :param int character_count: Number of characters in the input text. + :param str detected_language: (optional) The language code of the source text if the source language was automatically detected. - :attr float detected_language_confidence: (optional) A score between 0 and 1 + :param float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. - :attr List[Translation] translations: List of translation output in UTF-8, + :param List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ - def __init__(self, - word_count: int, - character_count: int, - translations: List['Translation'], - *, - detected_language: str = None, - detected_language_confidence: float = None) -> None: + def __init__( + self, + word_count: int, + character_count: int, + translations: List['Translation'], + *, + detected_language: Optional[str] = None, + detected_language_confidence: Optional[float] = None, + ) -> None: """ Initialize a TranslationResult object. @@ -2152,26 +2293,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') + if (word_count := _dict.get('word_count')) is not None: + args['word_count'] = word_count else: raise ValueError( 'Required property \'word_count\' not present in TranslationResult JSON' ) - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') + if (character_count := _dict.get('character_count')) is not None: + args['character_count'] = character_count else: raise ValueError( 'Required property \'character_count\' not present in TranslationResult JSON' ) - if 'detected_language' in _dict: - args['detected_language'] = _dict.get('detected_language') - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'translations' in _dict: + if (detected_language := _dict.get('detected_language')) is not None: + args['detected_language'] = detected_language + if (detected_language_confidence := + _dict.get('detected_language_confidence')) is not None: + args['detected_language_confidence'] = detected_language_confidence + if (translations := _dict.get('translations')) is not None: args['translations'] = [ - Translation.from_dict(v) for v in _dict.get('translations') + Translation.from_dict(v) for v in translations ] else: raise ValueError( diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index fd80a269..967e52c0 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2023. +# (C) Copyright IBM Corp. 2017, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -25,7 +25,7 @@ with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From -**June 1, 2023** onward, you will no longer be able to use the Custom Sentiment +**June 3, 2023** onward, you will no longer be able to use the Custom Sentiment feature.

To ensure we continue providing our clients with robust and powerful text classification capabilities, IBM recently announced the general availability of a new [single-label text classification @@ -40,7 +40,7 @@ from datetime import datetime from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -92,19 +92,21 @@ def __init__( # Analyze ######################### - def analyze(self, - features: 'Features', - *, - text: str = None, - html: str = None, - url: str = None, - clean: bool = None, - xpath: str = None, - fallback_to_raw: bool = None, - return_analyzed_text: bool = None, - language: str = None, - limit_text_characters: int = None, - **kwargs) -> DetailedResponse: + def analyze( + self, + features: 'Features', + *, + text: Optional[str] = None, + html: Optional[str] = None, + url: Optional[str] = None, + clean: Optional[bool] = None, + xpath: Optional[str] = None, + fallback_to_raw: Optional[bool] = None, + return_analyzed_text: Optional[bool] = None, + language: Optional[str] = None, + limit_text_characters: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Analyze text. @@ -160,9 +162,11 @@ def analyze(self, raise ValueError('features must be provided') features = convert_model(features) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='analyze') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='analyze', + ) headers.update(sdk_headers) params = { @@ -191,11 +195,13 @@ def analyze(self, headers['Accept'] = 'application/json' url = '/v1/analyze' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -204,7 +210,10 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -218,9 +227,11 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) params = { @@ -233,15 +244,21 @@ def list_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: + def delete_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete model. @@ -256,9 +273,11 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_model', + ) headers.update(sdk_headers) params = { @@ -274,10 +293,12 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -286,17 +307,20 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: # Manage categories models ######################### - def create_categories_model(self, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_categories_model( + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create categories model. @@ -311,6 +335,8 @@ def create_categories_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -325,12 +351,12 @@ def create_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_categories_model', + ) headers.update(sdk_headers) params = { @@ -344,6 +370,9 @@ def create_categories_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -362,16 +391,21 @@ def create_categories_model(self, headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_categories_models(self, **kwargs) -> DetailedResponse: + def list_categories_models( + self, + **kwargs, + ) -> DetailedResponse: """ List categories models. @@ -383,9 +417,11 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_categories_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_categories_models', + ) headers.update(sdk_headers) params = { @@ -398,15 +434,21 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get categories model details. @@ -421,9 +463,11 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_categories_model', + ) headers.update(sdk_headers) params = { @@ -439,26 +483,31 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_categories_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_categories_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update categories model. @@ -473,6 +522,8 @@ def update_categories_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -489,12 +540,12 @@ def update_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_categories_model', + ) headers.update(sdk_headers) params = { @@ -508,6 +559,9 @@ def update_categories_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -529,17 +583,22 @@ def update_categories_model(self, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_categories_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete categories model. @@ -555,9 +614,11 @@ def delete_categories_model(self, model_id: str, if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_categories_model', + ) headers.update(sdk_headers) params = { @@ -573,10 +634,12 @@ def delete_categories_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -586,18 +649,21 @@ def delete_categories_model(self, model_id: str, ######################### def create_classifications_model( - self, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - training_parameters: 'ClassificationsTrainingParameters' = None, - **kwargs) -> DetailedResponse: + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Create classifications model. @@ -612,6 +678,8 @@ def create_classifications_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -629,13 +697,12 @@ def create_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_classifications_model') + operation_id='create_classifications_model', + ) headers.update(sdk_headers) params = { @@ -649,6 +716,9 @@ def create_classifications_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -671,16 +741,21 @@ def create_classifications_model( headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_classifications_models(self, **kwargs) -> DetailedResponse: + def list_classifications_models( + self, + **kwargs, + ) -> DetailedResponse: """ List classifications models. @@ -695,7 +770,8 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='list_classifications_models') + operation_id='list_classifications_models', + ) headers.update(sdk_headers) params = { @@ -708,16 +784,21 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def get_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get classifications model details. @@ -732,9 +813,11 @@ def get_classifications_model(self, model_id: str, if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_classifications_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifications_model', + ) headers.update(sdk_headers) params = { @@ -750,28 +833,33 @@ def get_classifications_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def update_classifications_model( - self, - model_id: str, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - training_parameters: 'ClassificationsTrainingParameters' = None, - **kwargs) -> DetailedResponse: + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Update classifications model. @@ -786,6 +874,8 @@ def update_classifications_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -805,13 +895,12 @@ def update_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='update_classifications_model') + operation_id='update_classifications_model', + ) headers.update(sdk_headers) params = { @@ -825,6 +914,9 @@ def update_classifications_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -850,17 +942,22 @@ def update_classifications_model( path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete classifications model. @@ -879,7 +976,8 @@ def delete_classifications_model(self, model_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_classifications_model') + operation_id='delete_classifications_model', + ) headers.update(sdk_headers) params = { @@ -895,10 +993,12 @@ def delete_classifications_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -913,6 +1013,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -926,6 +1027,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -939,6 +1041,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -952,6 +1055,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -961,55 +1065,57 @@ class TrainingDataContentType(str, Enum): ############################################################################## -class AnalysisResults(): +class AnalysisResults: """ Results of the analysis, organized by feature. - :attr str language: (optional) Language used to analyze the text. - :attr str analyzed_text: (optional) Text that was used in the analysis. - :attr str retrieved_url: (optional) URL of the webpage that was analyzed. - :attr AnalysisResultsUsage usage: (optional) API usage information for the + :param str language: (optional) Language used to analyze the text. + :param str analyzed_text: (optional) Text that was used in the analysis. + :param str retrieved_url: (optional) URL of the webpage that was analyzed. + :param AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr List[ConceptsResult] concepts: (optional) The general concepts referenced + :param List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :attr List[EntitiesResult] entities: (optional) The entities detected in the + :param List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed + :param List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr List[CategoriesResult] categories: (optional) The categories that the + :param List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. - :attr List[ClassificationsResult] classifications: (optional) The + :param List[ClassificationsResult] classifications: (optional) The classifications assigned to the analyzed text. - :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. - :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :attr List[RelationsResult] relations: (optional) The relationships between + :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as + the author and the title of the page. + :param List[RelationsResult] relations: (optional) The relationships between entities in the content. - :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. - :attr SentimentResult sentiment: (optional) The sentiment of the content. - :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax + :param List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed + into `subject`, `action`, and `object` form. + :param SentimentResult sentiment: (optional) The sentiment of the content. + :param SyntaxResult syntax: (optional) Tokens and sentences returned from syntax analysis. """ - def __init__(self, - *, - language: str = None, - analyzed_text: str = None, - retrieved_url: str = None, - usage: 'AnalysisResultsUsage' = None, - concepts: List['ConceptsResult'] = None, - entities: List['EntitiesResult'] = None, - keywords: List['KeywordsResult'] = None, - categories: List['CategoriesResult'] = None, - classifications: List['ClassificationsResult'] = None, - emotion: 'EmotionResult' = None, - metadata: 'FeaturesResultsMetadata' = None, - relations: List['RelationsResult'] = None, - semantic_roles: List['SemanticRolesResult'] = None, - sentiment: 'SentimentResult' = None, - syntax: 'SyntaxResult' = None) -> None: + def __init__( + self, + *, + language: Optional[str] = None, + analyzed_text: Optional[str] = None, + retrieved_url: Optional[str] = None, + usage: Optional['AnalysisResultsUsage'] = None, + concepts: Optional[List['ConceptsResult']] = None, + entities: Optional[List['EntitiesResult']] = None, + keywords: Optional[List['KeywordsResult']] = None, + categories: Optional[List['CategoriesResult']] = None, + classifications: Optional[List['ClassificationsResult']] = None, + emotion: Optional['EmotionResult'] = None, + metadata: Optional['FeaturesResultsMetadata'] = None, + relations: Optional[List['RelationsResult']] = None, + semantic_roles: Optional[List['SemanticRolesResult']] = None, + sentiment: Optional['SentimentResult'] = None, + syntax: Optional['SyntaxResult'] = None, + ) -> None: """ Initialize a AnalysisResults object. @@ -1060,54 +1166,44 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'analyzed_text' in _dict: - args['analyzed_text'] = _dict.get('analyzed_text') - if 'retrieved_url' in _dict: - args['retrieved_url'] = _dict.get('retrieved_url') - if 'usage' in _dict: - args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) - if 'concepts' in _dict: - args['concepts'] = [ - ConceptsResult.from_dict(v) for v in _dict.get('concepts') - ] - if 'entities' in _dict: - args['entities'] = [ - EntitiesResult.from_dict(v) for v in _dict.get('entities') - ] - if 'keywords' in _dict: - args['keywords'] = [ - KeywordsResult.from_dict(v) for v in _dict.get('keywords') - ] - if 'categories' in _dict: + if (language := _dict.get('language')) is not None: + args['language'] = language + if (analyzed_text := _dict.get('analyzed_text')) is not None: + args['analyzed_text'] = analyzed_text + if (retrieved_url := _dict.get('retrieved_url')) is not None: + args['retrieved_url'] = retrieved_url + if (usage := _dict.get('usage')) is not None: + args['usage'] = AnalysisResultsUsage.from_dict(usage) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = [ConceptsResult.from_dict(v) for v in concepts] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [EntitiesResult.from_dict(v) for v in entities] + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = [KeywordsResult.from_dict(v) for v in keywords] + if (categories := _dict.get('categories')) is not None: args['categories'] = [ - CategoriesResult.from_dict(v) for v in _dict.get('categories') + CategoriesResult.from_dict(v) for v in categories ] - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = [ - ClassificationsResult.from_dict(v) - for v in _dict.get('classifications') + ClassificationsResult.from_dict(v) for v in classifications ] - if 'emotion' in _dict: - args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) - if 'metadata' in _dict: - args['metadata'] = FeaturesResultsMetadata.from_dict( - _dict.get('metadata')) - if 'relations' in _dict: + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionResult.from_dict(emotion) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = FeaturesResultsMetadata.from_dict(metadata) + if (relations := _dict.get('relations')) is not None: args['relations'] = [ - RelationsResult.from_dict(v) for v in _dict.get('relations') + RelationsResult.from_dict(v) for v in relations ] - if 'semantic_roles' in _dict: + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = [ - SemanticRolesResult.from_dict(v) - for v in _dict.get('semantic_roles') + SemanticRolesResult.from_dict(v) for v in semantic_roles ] - if 'sentiment' in _dict: - args['sentiment'] = SentimentResult.from_dict( - _dict.get('sentiment')) - if 'syntax' in _dict: - args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentResult.from_dict(sentiment) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxResult.from_dict(syntax) return cls(**args) @classmethod @@ -1227,20 +1323,22 @@ def __ne__(self, other: 'AnalysisResults') -> bool: return not self == other -class AnalysisResultsUsage(): +class AnalysisResultsUsage: """ API usage information for the request. - :attr int features: (optional) Number of features used in the API call. - :attr int text_characters: (optional) Number of text characters processed. - :attr int text_units: (optional) Number of 10,000-character units processed. + :param int features: (optional) Number of features used in the API call. + :param int text_characters: (optional) Number of text characters processed. + :param int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, - *, - features: int = None, - text_characters: int = None, - text_units: int = None) -> None: + def __init__( + self, + *, + features: Optional[int] = None, + text_characters: Optional[int] = None, + text_units: Optional[int] = None, + ) -> None: """ Initialize a AnalysisResultsUsage object. @@ -1257,12 +1355,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'text_characters' in _dict: - args['text_characters'] = _dict.get('text_characters') - if 'text_units' in _dict: - args['text_units'] = _dict.get('text_units') + if (features := _dict.get('features')) is not None: + args['features'] = features + if (text_characters := _dict.get('text_characters')) is not None: + args['text_characters'] = text_characters + if (text_units := _dict.get('text_units')) is not None: + args['text_units'] = text_units return cls(**args) @classmethod @@ -1301,14 +1399,18 @@ def __ne__(self, other: 'AnalysisResultsUsage') -> bool: return not self == other -class Author(): +class Author: """ The author of the analyzed content. - :attr str name: (optional) Name of the author. + :param str name: (optional) Name of the author. """ - def __init__(self, *, name: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + ) -> None: """ Initialize a Author object. @@ -1320,8 +1422,8 @@ def __init__(self, *, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -1355,47 +1457,49 @@ def __ne__(self, other: 'Author') -> bool: return not self == other -class CategoriesModel(): +class CategoriesModel: """ Categories model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a CategoriesModel object. @@ -1439,53 +1543,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesModel': """Initialize a CategoriesModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in CategoriesModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in CategoriesModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in CategoriesModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in CategoriesModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -1556,6 +1658,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -1564,14 +1667,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class CategoriesModelList(): +class CategoriesModelList: """ List of categories models. - :attr List[CategoriesModel] models: (optional) The categories models. + :param List[CategoriesModel] models: (optional) The categories models. """ - def __init__(self, *, models: List['CategoriesModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['CategoriesModel']] = None, + ) -> None: """ Initialize a CategoriesModelList object. @@ -1583,10 +1690,8 @@ def __init__(self, *, models: List['CategoriesModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': """Initialize a CategoriesModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - CategoriesModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [CategoriesModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -1626,27 +1731,29 @@ def __ne__(self, other: 'CategoriesModelList') -> bool: return not self == other -class CategoriesOptions(): +class CategoriesOptions: """ Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr bool explanation: (optional) Set this to `true` to return explanations for - each categorization. **This is available only for English categories.**. - :attr int limit: (optional) Maximum number of categories to return. - :attr str model: (optional) (Beta) Enter a [custom + :param bool explanation: (optional) Set this to `true` to return explanations + for each categorization. **This is available only for English categories.**. + :param int limit: (optional) Maximum number of categories to return. + :param str model: (optional) (Beta) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard categories model. **This is available only for English categories.**. """ - def __init__(self, - *, - explanation: bool = None, - limit: int = None, - model: str = None) -> None: + def __init__( + self, + *, + explanation: Optional[bool] = None, + limit: Optional[int] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a CategoriesOptions object. @@ -1667,12 +1774,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - if 'explanation' in _dict: - args['explanation'] = _dict.get('explanation') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (explanation := _dict.get('explanation')) is not None: + args['explanation'] = explanation + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -1710,15 +1817,19 @@ def __ne__(self, other: 'CategoriesOptions') -> bool: return not self == other -class CategoriesRelevantText(): +class CategoriesRelevantText: """ Relevant text that contributed to the categorization. - :attr str text: (optional) Text from the analyzed source that supports the + :param str text: (optional) Text from the analyzed source that supports the categorization. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a CategoriesRelevantText object. @@ -1731,8 +1842,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -1766,24 +1877,26 @@ def __ne__(self, other: 'CategoriesRelevantText') -> bool: return not self == other -class CategoriesResult(): +class CategoriesResult: """ A categorization of the analyzed text. - :attr str label: (optional) The path to the category through the multi-level + :param str label: (optional) The path to the category through the multi-level taxonomy hierarchy. For more information about the categories, see [Categories hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). - :attr float score: (optional) Confidence score for the category classification. + :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. - :attr CategoriesResultExplanation explanation: (optional) Information that helps - to explain what contributed to the categories result. + :param CategoriesResultExplanation explanation: (optional) Information that + helps to explain what contributed to the categories result. """ - def __init__(self, - *, - label: str = None, - score: float = None, - explanation: 'CategoriesResultExplanation' = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + explanation: Optional['CategoriesResultExplanation'] = None, + ) -> None: """ Initialize a CategoriesResult object. @@ -1804,13 +1917,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'explanation' in _dict: + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score + if (explanation := _dict.get('explanation')) is not None: args['explanation'] = CategoriesResultExplanation.from_dict( - _dict.get('explanation')) + explanation) return cls(**args) @classmethod @@ -1851,19 +1964,21 @@ def __ne__(self, other: 'CategoriesResult') -> bool: return not self == other -class CategoriesResultExplanation(): +class CategoriesResultExplanation: """ Information that helps to explain what contributed to the categories result. - :attr List[CategoriesRelevantText] relevant_text: (optional) An array of + :param List[CategoriesRelevantText] relevant_text: (optional) An array of relevant text from the source that contributed to the categorization. The sorted array begins with the phrase that contributed most significantly to the result, followed by phrases that were less and less impactful. """ - def __init__(self, - *, - relevant_text: List['CategoriesRelevantText'] = None) -> None: + def __init__( + self, + *, + relevant_text: Optional[List['CategoriesRelevantText']] = None, + ) -> None: """ Initialize a CategoriesResultExplanation object. @@ -1878,10 +1993,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - if 'relevant_text' in _dict: + if (relevant_text := _dict.get('relevant_text')) is not None: args['relevant_text'] = [ - CategoriesRelevantText.from_dict(v) - for v in _dict.get('relevant_text') + CategoriesRelevantText.from_dict(v) for v in relevant_text ] return cls(**args) @@ -1922,47 +2036,49 @@ def __ne__(self, other: 'CategoriesResultExplanation') -> bool: return not self == other -class ClassificationsModel(): +class ClassificationsModel: """ Classifications model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a ClassificationsModel object. @@ -2006,53 +2122,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': """Initialize a ClassificationsModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in ClassificationsModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in ClassificationsModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in ClassificationsModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in ClassificationsModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -2123,6 +2237,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -2131,14 +2246,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class ClassificationsModelList(): +class ClassificationsModelList: """ List of classifications models. - :attr List[ClassificationsModel] models: (optional) The classifications models. + :param List[ClassificationsModel] models: (optional) The classifications models. """ - def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['ClassificationsModel']] = None, + ) -> None: """ Initialize a ClassificationsModelList object. @@ -2151,10 +2270,8 @@ def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': """Initialize a ClassificationsModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - ClassificationsModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [ClassificationsModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -2194,11 +2311,11 @@ def __ne__(self, other: 'ClassificationsModelList') -> bool: return not self == other -class ClassificationsOptions(): +class ClassificationsOptions: """ Returns text classifications for the content. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID of the classifications model to be used. You can analyze tone by using a language-specific model ID. See [Tone analytics @@ -2206,7 +2323,11 @@ class ClassificationsOptions(): for more information. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a ClassificationsOptions object. @@ -2224,8 +2345,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsOptions': """Initialize a ClassificationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -2259,19 +2380,21 @@ def __ne__(self, other: 'ClassificationsOptions') -> bool: return not self == other -class ClassificationsResult(): +class ClassificationsResult: """ A classification of the analyzed text. - :attr str class_name: (optional) Classification assigned to the text. - :attr float confidence: (optional) Confidence score for the classification. + :param str class_name: (optional) Classification assigned to the text. + :param float confidence: (optional) Confidence score for the classification. Higher values indicate greater confidence. """ - def __init__(self, - *, - class_name: str = None, - confidence: float = None) -> None: + def __init__( + self, + *, + class_name: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ClassificationsResult object. @@ -2286,10 +2409,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsResult': """Initialize a ClassificationsResult object from a json dictionary.""" args = {} - if 'class_name' in _dict: - args['class_name'] = _dict.get('class_name') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (class_name := _dict.get('class_name')) is not None: + args['class_name'] = class_name + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -2325,15 +2448,19 @@ def __ne__(self, other: 'ClassificationsResult') -> bool: return not self == other -class ClassificationsTrainingParameters(): +class ClassificationsTrainingParameters: """ Optional classifications training parameters along with model train requests. - :attr str model_type: (optional) Model type selector to train either a + :param str model_type: (optional) Model type selector to train either a single_label or a multi_label classifier. """ - def __init__(self, *, model_type: str = None) -> None: + def __init__( + self, + *, + model_type: Optional[str] = None, + ) -> None: """ Initialize a ClassificationsTrainingParameters object. @@ -2346,8 +2473,8 @@ def __init__(self, *, model_type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsTrainingParameters': """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" args = {} - if 'model_type' in _dict: - args['model_type'] = _dict.get('model_type') + if (model_type := _dict.get('model_type')) is not None: + args['model_type'] = model_type return cls(**args) @classmethod @@ -2384,11 +2511,12 @@ class ModelTypeEnum(str, Enum): """ Model type selector to train either a single_label or a multi_label classifier. """ + SINGLE_LABEL = 'single_label' MULTI_LABEL = 'multi_label' -class ConceptsOptions(): +class ConceptsOptions: """ Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not @@ -2396,10 +2524,14 @@ class ConceptsOptions(): Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr int limit: (optional) Maximum number of concepts to return. + :param int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a ConceptsOptions object. @@ -2411,8 +2543,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -2446,22 +2578,24 @@ def __ne__(self, other: 'ConceptsOptions') -> bool: return not self == other -class ConceptsResult(): +class ConceptsResult: """ The general concepts referenced or alluded to in the analyzed text. - :attr str text: (optional) Name of the concept. - :attr float relevance: (optional) Relevance score between 0 and 1. Higher scores - indicate greater relevance. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str text: (optional) Name of the concept. + :param float relevance: (optional) Relevance score between 0 and 1. Higher + scores indicate greater relevance. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. """ - def __init__(self, - *, - text: str = None, - relevance: float = None, - dbpedia_resource: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + relevance: Optional[float] = None, + dbpedia_resource: Optional[str] = None, + ) -> None: """ Initialize a ConceptsResult object. @@ -2479,12 +2613,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource return cls(**args) @classmethod @@ -2523,14 +2657,18 @@ def __ne__(self, other: 'ConceptsResult') -> bool: return not self == other -class DeleteModelResults(): +class DeleteModelResults: """ Delete model results. - :attr str deleted: (optional) model_id of the deleted model. + :param str deleted: (optional) model_id of the deleted model. """ - def __init__(self, *, deleted: str = None) -> None: + def __init__( + self, + *, + deleted: Optional[str] = None, + ) -> None: """ Initialize a DeleteModelResults object. @@ -2542,8 +2680,8 @@ def __init__(self, *, deleted: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} - if 'deleted' in _dict: - args['deleted'] = _dict.get('deleted') + if (deleted := _dict.get('deleted')) is not None: + args['deleted'] = deleted return cls(**args) @classmethod @@ -2577,21 +2715,23 @@ def __ne__(self, other: 'DeleteModelResults') -> bool: return not self == other -class DisambiguationResult(): +class DisambiguationResult: """ Disambiguation information for the entity. - :attr str name: (optional) Common entity name. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str name: (optional) Common entity name. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :attr List[str] subtype: (optional) Entity subtype information. + :param List[str] subtype: (optional) Entity subtype information. """ - def __init__(self, - *, - name: str = None, - dbpedia_resource: str = None, - subtype: List[str] = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + dbpedia_resource: Optional[str] = None, + subtype: Optional[List[str]] = None, + ) -> None: """ Initialize a DisambiguationResult object. @@ -2608,12 +2748,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype return cls(**args) @classmethod @@ -2652,15 +2792,19 @@ def __ne__(self, other: 'DisambiguationResult') -> bool: return not self == other -class DocumentEmotionResults(): +class DocumentEmotionResults: """ Emotion results for the document as a whole. - :attr EmotionScores emotion: (optional) Emotion results for the document as a + :param EmotionScores emotion: (optional) Emotion results for the document as a whole. """ - def __init__(self, *, emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a DocumentEmotionResults object. @@ -2673,8 +2817,8 @@ def __init__(self, *, emotion: 'EmotionScores' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -2711,17 +2855,22 @@ def __ne__(self, other: 'DocumentEmotionResults') -> bool: return not self == other -class DocumentSentimentResults(): +class DocumentSentimentResults: """ DocumentSentimentResults. - :attr str label: (optional) Indicates whether the sentiment is positive, + :param str label: (optional) Indicates whether the sentiment is positive, neutral, or negative. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, label: str = None, score: float = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a DocumentSentimentResults object. @@ -2737,10 +2886,10 @@ def __init__(self, *, label: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -2776,7 +2925,7 @@ def __ne__(self, other: 'DocumentSentimentResults') -> bool: return not self == other -class EmotionOptions(): +class EmotionOptions: """ Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze @@ -2784,16 +2933,18 @@ class EmotionOptions(): `keywords.emotion`. Supported languages: English. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level emotion results. - :attr List[str] targets: (optional) Emotion results will be returned for each + :param List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a EmotionOptions object. @@ -2809,10 +2960,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -2848,22 +2999,24 @@ def __ne__(self, other: 'EmotionOptions') -> bool: return not self == other -class EmotionResult(): +class EmotionResult: """ The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. - :attr DocumentEmotionResults document: (optional) Emotion results for the + :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :attr List[TargetedEmotionResults] targets: (optional) Emotion results for + :param List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ - def __init__(self, - *, - document: 'DocumentEmotionResults' = None, - targets: List['TargetedEmotionResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentEmotionResults'] = None, + targets: Optional[List['TargetedEmotionResults']] = None, + ) -> None: """ Initialize a EmotionResult object. @@ -2879,13 +3032,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentEmotionResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentEmotionResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedEmotionResults.from_dict(v) - for v in _dict.get('targets') + TargetedEmotionResults.from_dict(v) for v in targets ] return cls(**args) @@ -2931,29 +3082,31 @@ def __ne__(self, other: 'EmotionResult') -> bool: return not self == other -class EmotionScores(): +class EmotionScores: """ EmotionScores. - :attr float anger: (optional) Anger score from 0 to 1. A higher score means that - the text is more likely to convey anger. - :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means + :param float anger: (optional) Anger score from 0 to 1. A higher score means + that the text is more likely to convey anger. + :param float disgust: (optional) Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. - :attr float fear: (optional) Fear score from 0 to 1. A higher score means that + :param float fear: (optional) Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. - :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the - text is more likely to convey joy. - :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means + :param float joy: (optional) Joy score from 0 to 1. A higher score means that + the text is more likely to convey joy. + :param float sadness: (optional) Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. """ - def __init__(self, - *, - anger: float = None, - disgust: float = None, - fear: float = None, - joy: float = None, - sadness: float = None) -> None: + def __init__( + self, + *, + anger: Optional[float] = None, + disgust: Optional[float] = None, + fear: Optional[float] = None, + joy: Optional[float] = None, + sadness: Optional[float] = None, + ) -> None: """ Initialize a EmotionScores object. @@ -2978,16 +3131,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} - if 'anger' in _dict: - args['anger'] = _dict.get('anger') - if 'disgust' in _dict: - args['disgust'] = _dict.get('disgust') - if 'fear' in _dict: - args['fear'] = _dict.get('fear') - if 'joy' in _dict: - args['joy'] = _dict.get('joy') - if 'sadness' in _dict: - args['sadness'] = _dict.get('sadness') + if (anger := _dict.get('anger')) is not None: + args['anger'] = anger + if (disgust := _dict.get('disgust')) is not None: + args['disgust'] = disgust + if (fear := _dict.get('fear')) is not None: + args['fear'] = fear + if (joy := _dict.get('joy')) is not None: + args['joy'] = joy + if (sadness := _dict.get('sadness')) is not None: + args['sadness'] = sadness return cls(**args) @classmethod @@ -3029,34 +3182,36 @@ def __ne__(self, other: 'EmotionScores') -> bool: return not self == other -class EntitiesOptions(): +class EntitiesOptions: """ Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr int limit: (optional) Maximum number of entities to return. - :attr bool mentions: (optional) Set this to `true` to return locations of entity - mentions. - :attr str model: (optional) Enter a [custom + :param int limit: (optional) Maximum number of entities to return. + :param bool mentions: (optional) Set this to `true` to return locations of + entity mentions. + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard entity detection model. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - mentions: bool = None, - model: str = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + mentions: Optional[bool] = None, + model: Optional[str] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a EntitiesOptions object. @@ -3081,16 +3236,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'model' in _dict: - args['model'] = _dict.get('model') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = mentions + if (model := _dict.get('model')) is not None: + args['model'] = model + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3132,40 +3287,43 @@ def __ne__(self, other: 'EntitiesOptions') -> bool: return not self == other -class EntitiesResult(): +class EntitiesResult: """ The important people, places, geopolitical entities and other types of entities in your content. - :attr str type: (optional) Entity type. - :attr str text: (optional) The name of the entity. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param str type: (optional) Entity type. + :param str text: (optional) The name of the entity. + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. - :attr List[EntityMention] mentions: (optional) Entity mentions and locations. - :attr int count: (optional) How many times the entity was mentioned in the text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, - enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param List[EntityMention] mentions: (optional) Entity mentions and locations. + :param int count: (optional) How many times the entity was mentioned in the + text. + :param EmotionScores emotion: (optional) Emotion analysis results for the + entity, enabled with the `emotion` option. + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the entity, enabled with the `sentiment` option. - :attr DisambiguationResult disambiguation: (optional) Disambiguation information - for the entity. + :param DisambiguationResult disambiguation: (optional) Disambiguation + information for the entity. """ - def __init__(self, - *, - type: str = None, - text: str = None, - relevance: float = None, - confidence: float = None, - mentions: List['EntityMention'] = None, - count: int = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None, - disambiguation: 'DisambiguationResult' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + relevance: Optional[float] = None, + confidence: Optional[float] = None, + mentions: Optional[List['EntityMention']] = None, + count: Optional[int] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + disambiguation: Optional['DisambiguationResult'] = None, + ) -> None: """ Initialize a EntitiesResult object. @@ -3202,28 +3360,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'mentions' in _dict: - args['mentions'] = [ - EntityMention.from_dict(v) for v in _dict.get('mentions') - ] - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) - if 'disambiguation' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [EntityMention.from_dict(v) for v in mentions] + if (count := _dict.get('count')) is not None: + args['count'] = count + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) + if (disambiguation := _dict.get('disambiguation')) is not None: args['disambiguation'] = DisambiguationResult.from_dict( - _dict.get('disambiguation')) + disambiguation) return cls(**args) @classmethod @@ -3288,24 +3443,26 @@ def __ne__(self, other: 'EntitiesResult') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ EntityMention. - :attr str text: (optional) Entity mention text. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) Entity mention text. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. """ - def __init__(self, - *, - text: str = None, - location: List[int] = None, - confidence: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a EntityMention object. @@ -3325,12 +3482,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -3368,15 +3525,19 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class FeatureSentimentResults(): +class FeatureSentimentResults: """ FeatureSentimentResults. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, score: float = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + ) -> None: """ Initialize a FeatureSentimentResults object. @@ -3389,8 +3550,8 @@ def __init__(self, *, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -3424,37 +3585,37 @@ def __ne__(self, other: 'FeatureSentimentResults') -> bool: return not self == other -class Features(): +class Features: """ Analysis features and options. - :attr ClassificationsOptions classifications: (optional) Returns text + :param ClassificationsOptions classifications: (optional) Returns text classifications for the content. - :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the + :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or + :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. - :attr EntitiesOptions entities: (optional) Identifies people, cities, + :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr KeywordsOptions keywords: (optional) Returns important keywords in the + :param KeywordsOptions keywords: (optional) Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr dict metadata: (optional) Returns information from the document, including - author name, title, RSS/ATOM feeds, prominent page image, and publication date. - Supports URL and HTML input types only. - :attr RelationsOptions relations: (optional) Recognizes when two entities are + :param dict metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. + :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For more information, see [Relation @@ -3462,41 +3623,43 @@ class Features(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into + :param SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of + :param SentimentOptions sentiment: (optional) Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr SummarizationOptions summarization: (optional) (Experimental) Returns a + :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. Supported regions: Dallas region only. - :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy + :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the + :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ - def __init__(self, - *, - classifications: 'ClassificationsOptions' = None, - concepts: 'ConceptsOptions' = None, - emotion: 'EmotionOptions' = None, - entities: 'EntitiesOptions' = None, - keywords: 'KeywordsOptions' = None, - metadata: dict = None, - relations: 'RelationsOptions' = None, - semantic_roles: 'SemanticRolesOptions' = None, - sentiment: 'SentimentOptions' = None, - summarization: 'SummarizationOptions' = None, - categories: 'CategoriesOptions' = None, - syntax: 'SyntaxOptions' = None) -> None: + def __init__( + self, + *, + classifications: Optional['ClassificationsOptions'] = None, + concepts: Optional['ConceptsOptions'] = None, + emotion: Optional['EmotionOptions'] = None, + entities: Optional['EntitiesOptions'] = None, + keywords: Optional['KeywordsOptions'] = None, + metadata: Optional[dict] = None, + relations: Optional['RelationsOptions'] = None, + semantic_roles: Optional['SemanticRolesOptions'] = None, + sentiment: Optional['SentimentOptions'] = None, + summarization: Optional['SummarizationOptions'] = None, + categories: Optional['CategoriesOptions'] = None, + syntax: Optional['SyntaxOptions'] = None, + ) -> None: """ Initialize a Features object. @@ -3516,7 +3679,7 @@ def __init__(self, :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -3572,36 +3735,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = ClassificationsOptions.from_dict( - _dict.get('classifications')) - if 'concepts' in _dict: - args['concepts'] = ConceptsOptions.from_dict(_dict.get('concepts')) - if 'emotion' in _dict: - args['emotion'] = EmotionOptions.from_dict(_dict.get('emotion')) - if 'entities' in _dict: - args['entities'] = EntitiesOptions.from_dict(_dict.get('entities')) - if 'keywords' in _dict: - args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'relations' in _dict: - args['relations'] = RelationsOptions.from_dict( - _dict.get('relations')) - if 'semantic_roles' in _dict: + classifications) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = ConceptsOptions.from_dict(concepts) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionOptions.from_dict(emotion) + if (entities := _dict.get('entities')) is not None: + args['entities'] = EntitiesOptions.from_dict(entities) + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = KeywordsOptions.from_dict(keywords) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (relations := _dict.get('relations')) is not None: + args['relations'] = RelationsOptions.from_dict(relations) + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = SemanticRolesOptions.from_dict( - _dict.get('semantic_roles')) - if 'sentiment' in _dict: - args['sentiment'] = SentimentOptions.from_dict( - _dict.get('sentiment')) - if 'summarization' in _dict: + semantic_roles) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentOptions.from_dict(sentiment) + if (summarization := _dict.get('summarization')) is not None: args['summarization'] = SummarizationOptions.from_dict( - _dict.get('summarization')) - if 'categories' in _dict: - args['categories'] = CategoriesOptions.from_dict( - _dict.get('categories')) - if 'syntax' in _dict: - args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) + summarization) + if (categories := _dict.get('categories')) is not None: + args['categories'] = CategoriesOptions.from_dict(categories) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxOptions.from_dict(syntax) return cls(**args) @classmethod @@ -3691,25 +3851,27 @@ def __ne__(self, other: 'Features') -> bool: return not self == other -class FeaturesResultsMetadata(): +class FeaturesResultsMetadata: """ Webpage metadata, such as the author and the title of the page. - :attr List[Author] authors: (optional) The authors of the document. - :attr str publication_date: (optional) The publication date in the format ISO + :param List[Author] authors: (optional) The authors of the document. + :param str publication_date: (optional) The publication date in the format ISO 8601. - :attr str title: (optional) The title of the document. - :attr str image: (optional) URL of a prominent image on the webpage. - :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + :param str title: (optional) The title of the document. + :param str image: (optional) URL of a prominent image on the webpage. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ - def __init__(self, - *, - authors: List['Author'] = None, - publication_date: str = None, - title: str = None, - image: str = None, - feeds: List['Feed'] = None) -> None: + def __init__( + self, + *, + authors: Optional[List['Author']] = None, + publication_date: Optional[str] = None, + title: Optional[str] = None, + image: Optional[str] = None, + feeds: Optional[List['Feed']] = None, + ) -> None: """ Initialize a FeaturesResultsMetadata object. @@ -3730,18 +3892,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': """Initialize a FeaturesResultsMetadata object from a json dictionary.""" args = {} - if 'authors' in _dict: - args['authors'] = [ - Author.from_dict(v) for v in _dict.get('authors') - ] - if 'publication_date' in _dict: - args['publication_date'] = _dict.get('publication_date') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'feeds' in _dict: - args['feeds'] = [Feed.from_dict(v) for v in _dict.get('feeds')] + if (authors := _dict.get('authors')) is not None: + args['authors'] = [Author.from_dict(v) for v in authors] + if (publication_date := _dict.get('publication_date')) is not None: + args['publication_date'] = publication_date + if (title := _dict.get('title')) is not None: + args['title'] = title + if (image := _dict.get('image')) is not None: + args['image'] = image + if (feeds := _dict.get('feeds')) is not None: + args['feeds'] = [Feed.from_dict(v) for v in feeds] return cls(**args) @classmethod @@ -3796,14 +3956,18 @@ def __ne__(self, other: 'FeaturesResultsMetadata') -> bool: return not self == other -class Feed(): +class Feed: """ RSS or ATOM feed found on the webpage. - :attr str link: (optional) URL of the RSS or ATOM feed. + :param str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, *, link: str = None) -> None: + def __init__( + self, + *, + link: Optional[str] = None, + ) -> None: """ Initialize a Feed object. @@ -3815,8 +3979,8 @@ def __init__(self, *, link: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} - if 'link' in _dict: - args['link'] = _dict.get('link') + if (link := _dict.get('link')) is not None: + args['link'] = link return cls(**args) @classmethod @@ -3850,24 +4014,26 @@ def __ne__(self, other: 'Feed') -> bool: return not self == other -class KeywordsOptions(): +class KeywordsOptions: """ Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr int limit: (optional) Maximum number of keywords to return. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param int limit: (optional) Maximum number of keywords to return. + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected keywords. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a KeywordsOptions object. @@ -3885,12 +4051,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3928,28 +4094,30 @@ def __ne__(self, other: 'KeywordsOptions') -> bool: return not self == other -class KeywordsResult(): +class KeywordsResult: """ The important keywords in the content, organized by relevance. - :attr int count: (optional) Number of times the keyword appears in the analyzed + :param int count: (optional) Number of times the keyword appears in the analyzed text. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr str text: (optional) The keyword text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the + :param str text: (optional) The keyword text. + :param EmotionScores emotion: (optional) Emotion analysis results for the keyword, enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the keyword, enabled with the `sentiment` option. """ - def __init__(self, - *, - count: int = None, - relevance: float = None, - text: str = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None) -> None: + def __init__( + self, + *, + count: Optional[int] = None, + relevance: Optional[float] = None, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + ) -> None: """ Initialize a KeywordsResult object. @@ -3973,17 +4141,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) + if (count := _dict.get('count')) is not None: + args['count'] = count + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) return cls(**args) @classmethod @@ -4031,14 +4198,18 @@ def __ne__(self, other: 'KeywordsResult') -> bool: return not self == other -class ListModelsResults(): +class ListModelsResults: """ Custom models that are available for entities and relations. - :attr List[Model] models: (optional) An array of available models. + :param List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models: List['Model'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['Model']] = None, + ) -> None: """ Initialize a ListModelsResults object. @@ -4050,8 +4221,8 @@ def __init__(self, *, models: List['Model'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [Model.from_dict(v) for v in _dict.get('models')] + if (models := _dict.get('models')) is not None: + args['models'] = [Model.from_dict(v) for v in models] return cls(**args) @classmethod @@ -4091,38 +4262,40 @@ def __ne__(self, other: 'ListModelsResults') -> bool: return not self == other -class Model(): +class Model: """ Model. - :attr str status: (optional) When the status is `available`, the model is ready + :param str status: (optional) When the status is `available`, the model is ready to use. - :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code that indicates the language of the - model. - :attr str description: (optional) Model description. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str model_id: (optional) Unique model ID. + :param str language: (optional) ISO 639-1 code that indicates the language of + the model. + :param str description: (optional) Model description. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str model_version: (optional) The model version, if it was manually + :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) Deprecated: Deprecated — use `model_version`. - :attr str version_description: (optional) The description of the version, if it + :param str version: (optional) Deprecated: Deprecated — use `model_version`. + :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. - :attr datetime created: (optional) A dateTime indicating when the model was + :param datetime created: (optional) A dateTime indicating when the model was created. """ - def __init__(self, - *, - status: str = None, - model_id: str = None, - language: str = None, - description: str = None, - workspace_id: str = None, - model_version: str = None, - version: str = None, - version_description: str = None, - created: datetime = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + model_id: Optional[str] = None, + language: Optional[str] = None, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + model_version: Optional[str] = None, + version: Optional[str] = None, + version_description: Optional[str] = None, + created: Optional[datetime] = None, + ) -> None: """ Initialize a Model object. @@ -4157,24 +4330,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'version' in _dict: - args['version'] = _dict.get('version') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (language := _dict.get('language')) is not None: + args['language'] = language + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (version := _dict.get('version')) is not None: + args['version'] = version + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) return cls(**args) @classmethod @@ -4229,6 +4403,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -4237,15 +4412,19 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class Notice(): +class Notice: """ A list of messages describing model training issues when model status is `error`. - :attr str message: (optional) Describes deficiencies or inconsistencies in + :param str message: (optional) Describes deficiencies or inconsistencies in training data. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -4256,8 +4435,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -4291,21 +4470,23 @@ def __ne__(self, other: 'Notice') -> bool: return not self == other -class RelationArgument(): +class RelationArgument: """ RelationArgument. - :attr List[RelationEntity] entities: (optional) An array of extracted entities. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[RelationEntity] entities: (optional) An array of extracted entities. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr str text: (optional) Text that corresponds to the argument. + :param str text: (optional) Text that corresponds to the argument. """ - def __init__(self, - *, - entities: List['RelationEntity'] = None, - location: List[int] = None, - text: str = None) -> None: + def __init__( + self, + *, + entities: Optional[List['RelationEntity']] = None, + location: Optional[List[int]] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a RelationArgument object. @@ -4323,14 +4504,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - RelationEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RelationEntity.from_dict(v) for v in entities] + if (location := _dict.get('location')) is not None: + args['location'] = location + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4374,15 +4553,20 @@ def __ne__(self, other: 'RelationArgument') -> bool: return not self == other -class RelationEntity(): +class RelationEntity: """ An entity that corresponds with an argument in a relation. - :attr str text: (optional) Text that corresponds to the entity. - :attr str type: (optional) Entity type. + :param str text: (optional) Text that corresponds to the entity. + :param str type: (optional) Entity type. """ - def __init__(self, *, text: str = None, type: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a RelationEntity object. @@ -4396,10 +4580,10 @@ def __init__(self, *, text: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -4435,7 +4619,7 @@ def __ne__(self, other: 'RelationEntity') -> bool: return not self == other -class RelationsOptions(): +class RelationsOptions: """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -4444,12 +4628,16 @@ class RelationsOptions(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the default model. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a RelationsOptions object. @@ -4463,8 +4651,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -4498,24 +4686,26 @@ def __ne__(self, other: 'RelationsOptions') -> bool: return not self == other -class RelationsResult(): +class RelationsResult: """ The relations between entities found in the content. - :attr float score: (optional) Confidence score for the relation. Higher values + :param float score: (optional) Confidence score for the relation. Higher values indicate greater confidence. - :attr str sentence: (optional) The sentence that contains the relation. - :attr str type: (optional) The type of the relation. - :attr List[RelationArgument] arguments: (optional) Entity mentions that are + :param str sentence: (optional) The sentence that contains the relation. + :param str type: (optional) The type of the relation. + :param List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ - def __init__(self, - *, - score: float = None, - sentence: str = None, - type: str = None, - arguments: List['RelationArgument'] = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + sentence: Optional[str] = None, + type: Optional[str] = None, + arguments: Optional[List['RelationArgument']] = None, + ) -> None: """ Initialize a RelationsResult object. @@ -4535,15 +4725,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'arguments' in _dict: + if (score := _dict.get('score')) is not None: + args['score'] = score + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (type := _dict.get('type')) is not None: + args['type'] = type + if (arguments := _dict.get('arguments')) is not None: args['arguments'] = [ - RelationArgument.from_dict(v) for v in _dict.get('arguments') + RelationArgument.from_dict(v) for v in arguments ] return cls(**args) @@ -4590,15 +4780,20 @@ def __ne__(self, other: 'RelationsResult') -> bool: return not self == other -class SemanticRolesEntity(): +class SemanticRolesEntity: """ SemanticRolesEntity. - :attr str type: (optional) Entity type. - :attr str text: (optional) The entity text. + :param str type: (optional) Entity type. + :param str text: (optional) The entity text. """ - def __init__(self, *, type: str = None, text: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesEntity object. @@ -4612,10 +4807,10 @@ def __init__(self, *, type: str = None, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4651,14 +4846,18 @@ def __ne__(self, other: 'SemanticRolesEntity') -> bool: return not self == other -class SemanticRolesKeyword(): +class SemanticRolesKeyword: """ SemanticRolesKeyword. - :attr str text: (optional) The keyword text. + :param str text: (optional) The keyword text. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesKeyword object. @@ -4670,8 +4869,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4705,23 +4904,25 @@ def __ne__(self, other: 'SemanticRolesKeyword') -> bool: return not self == other -class SemanticRolesOptions(): +class SemanticRolesOptions: """ Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr int limit: (optional) Maximum number of semantic_roles results to return. - :attr bool keywords: (optional) Set this to `true` to return keyword information - for subjects and objects. - :attr bool entities: (optional) Set this to `true` to return entity information + :param int limit: (optional) Maximum number of semantic_roles results to return. + :param bool keywords: (optional) Set this to `true` to return keyword + information for subjects and objects. + :param bool entities: (optional) Set this to `true` to return entity information for subjects and objects. """ - def __init__(self, - *, - limit: int = None, - keywords: bool = None, - entities: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + keywords: Optional[bool] = None, + entities: Optional[bool] = None, + ) -> None: """ Initialize a SemanticRolesOptions object. @@ -4740,12 +4941,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'entities' in _dict: - args['entities'] = _dict.get('entities') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = keywords + if (entities := _dict.get('entities')) is not None: + args['entities'] = entities return cls(**args) @classmethod @@ -4783,26 +4984,28 @@ def __ne__(self, other: 'SemanticRolesOptions') -> bool: return not self == other -class SemanticRolesResult(): +class SemanticRolesResult: """ The object containing the actions and the objects the actions act upon. - :attr str sentence: (optional) Sentence from the source that contains the + :param str sentence: (optional) Sentence from the source that contains the subject, action, and object. - :attr SemanticRolesResultSubject subject: (optional) The extracted subject from + :param SemanticRolesResultSubject subject: (optional) The extracted subject from + the sentence. + :param SemanticRolesResultAction action: (optional) The extracted action from + the sentence. + :param SemanticRolesResultObject object: (optional) The extracted object from the sentence. - :attr SemanticRolesResultAction action: (optional) The extracted action from the - sentence. - :attr SemanticRolesResultObject object: (optional) The extracted object from the - sentence. """ - def __init__(self, - *, - sentence: str = None, - subject: 'SemanticRolesResultSubject' = None, - action: 'SemanticRolesResultAction' = None, - object: 'SemanticRolesResultObject' = None) -> None: + def __init__( + self, + *, + sentence: Optional[str] = None, + subject: Optional['SemanticRolesResultSubject'] = None, + action: Optional['SemanticRolesResultAction'] = None, + object: Optional['SemanticRolesResultObject'] = None, + ) -> None: """ Initialize a SemanticRolesResult object. @@ -4824,17 +5027,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'subject' in _dict: - args['subject'] = SemanticRolesResultSubject.from_dict( - _dict.get('subject')) - if 'action' in _dict: - args['action'] = SemanticRolesResultAction.from_dict( - _dict.get('action')) - if 'object' in _dict: - args['object'] = SemanticRolesResultObject.from_dict( - _dict.get('object')) + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (subject := _dict.get('subject')) is not None: + args['subject'] = SemanticRolesResultSubject.from_dict(subject) + if (action := _dict.get('action')) is not None: + args['action'] = SemanticRolesResultAction.from_dict(action) + if (object := _dict.get('object')) is not None: + args['object'] = SemanticRolesResultObject.from_dict(object) return cls(**args) @classmethod @@ -4883,20 +5083,22 @@ def __ne__(self, other: 'SemanticRolesResult') -> bool: return not self == other -class SemanticRolesResultAction(): +class SemanticRolesResultAction: """ The extracted action from the sentence. - :attr str text: (optional) Analyzed text that corresponds to the action. - :attr str normalized: (optional) normalized version of the action. - :attr SemanticRolesVerb verb: (optional) + :param str text: (optional) Analyzed text that corresponds to the action. + :param str normalized: (optional) normalized version of the action. + :param SemanticRolesVerb verb: (optional) """ - def __init__(self, - *, - text: str = None, - normalized: str = None, - verb: 'SemanticRolesVerb' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + normalized: Optional[str] = None, + verb: Optional['SemanticRolesVerb'] = None, + ) -> None: """ Initialize a SemanticRolesResultAction object. @@ -4912,12 +5114,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'normalized' in _dict: - args['normalized'] = _dict.get('normalized') - if 'verb' in _dict: - args['verb'] = SemanticRolesVerb.from_dict(_dict.get('verb')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (normalized := _dict.get('normalized')) is not None: + args['normalized'] = normalized + if (verb := _dict.get('verb')) is not None: + args['verb'] = SemanticRolesVerb.from_dict(verb) return cls(**args) @classmethod @@ -4958,19 +5160,21 @@ def __ne__(self, other: 'SemanticRolesResultAction') -> bool: return not self == other -class SemanticRolesResultObject(): +class SemanticRolesResultObject: """ The extracted object from the sentence. - :attr str text: (optional) Object text. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param str text: (optional) Object text. + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultObject object. @@ -4985,11 +5189,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'keywords' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -5032,22 +5236,24 @@ def __ne__(self, other: 'SemanticRolesResultObject') -> bool: return not self == other -class SemanticRolesResultSubject(): +class SemanticRolesResultSubject: """ The extracted subject from the sentence. - :attr str text: (optional) Text that corresponds to the subject role. - :attr List[SemanticRolesEntity] entities: (optional) An array of extracted + :param str text: (optional) Text that corresponds to the subject role. + :param List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - entities: List['SemanticRolesEntity'] = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + entities: Optional[List['SemanticRolesEntity']] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultSubject object. @@ -5065,15 +5271,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'entities' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (entities := _dict.get('entities')) is not None: args['entities'] = [ - SemanticRolesEntity.from_dict(v) for v in _dict.get('entities') + SemanticRolesEntity.from_dict(v) for v in entities ] - if 'keywords' in _dict: + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -5124,15 +5330,20 @@ def __ne__(self, other: 'SemanticRolesResultSubject') -> bool: return not self == other -class SemanticRolesVerb(): +class SemanticRolesVerb: """ SemanticRolesVerb. - :attr str text: (optional) The keyword text. - :attr str tense: (optional) Verb tense. + :param str text: (optional) The keyword text. + :param str tense: (optional) Verb tense. """ - def __init__(self, *, text: str = None, tense: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + tense: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesVerb object. @@ -5146,10 +5357,10 @@ def __init__(self, *, text: str = None, tense: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'tense' in _dict: - args['tense'] = _dict.get('tense') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (tense := _dict.get('tense')) is not None: + args['tense'] = tense return cls(**args) @classmethod @@ -5185,16 +5396,21 @@ def __ne__(self, other: 'SemanticRolesVerb') -> bool: return not self == other -class SentenceResult(): +class SentenceResult: """ SentenceResult. - :attr str text: (optional) The sentence. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) The sentence. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ - def __init__(self, *, text: str = None, location: List[int] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a SentenceResult object. @@ -5209,10 +5425,10 @@ def __init__(self, *, text: str = None, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -5248,7 +5464,7 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other -class SentimentOptions(): +class SentimentOptions: """ Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and @@ -5256,16 +5472,18 @@ class SentimentOptions(): Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level sentiment results. - :attr List[str] targets: (optional) Sentiment results will be returned for each + :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a SentimentOptions object. @@ -5281,10 +5499,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -5320,20 +5538,22 @@ def __ne__(self, other: 'SentimentOptions') -> bool: return not self == other -class SentimentResult(): +class SentimentResult: """ The sentiment of the content. - :attr DocumentSentimentResults document: (optional) The document level + :param DocumentSentimentResults document: (optional) The document level sentiment. - :attr List[TargetedSentimentResults] targets: (optional) The targeted sentiment + :param List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ - def __init__(self, - *, - document: 'DocumentSentimentResults' = None, - targets: List['TargetedSentimentResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentSentimentResults'] = None, + targets: Optional[List['TargetedSentimentResults']] = None, + ) -> None: """ Initialize a SentimentResult object. @@ -5349,13 +5569,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentSentimentResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentSentimentResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedSentimentResults.from_dict(v) - for v in _dict.get('targets') + TargetedSentimentResults.from_dict(v) for v in targets ] return cls(**args) @@ -5401,16 +5619,20 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other -class SummarizationOptions(): +class SummarizationOptions: """ (Experimental) Returns a summary of content. Supported languages: English only. Supported regions: Dallas region only. - :attr int limit: (optional) Maximum number of summary sentences to return. + :param int limit: (optional) Maximum number of summary sentences to return. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SummarizationOptions object. @@ -5422,8 +5644,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': """Initialize a SummarizationOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -5457,19 +5679,21 @@ def __ne__(self, other: 'SummarizationOptions') -> bool: return not self == other -class SyntaxOptions(): +class SyntaxOptions: """ Returns tokens and sentences from the input text. - :attr SyntaxOptionsTokens tokens: (optional) Tokenization options. - :attr bool sentences: (optional) Set this to `true` to return sentence + :param SyntaxOptionsTokens tokens: (optional) Tokenization options. + :param bool sentences: (optional) Set this to `true` to return sentence information. """ - def __init__(self, - *, - tokens: 'SyntaxOptionsTokens' = None, - sentences: bool = None) -> None: + def __init__( + self, + *, + tokens: Optional['SyntaxOptionsTokens'] = None, + sentences: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptions object. @@ -5484,10 +5708,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = SyntaxOptionsTokens.from_dict(_dict.get('tokens')) - if 'sentences' in _dict: - args['sentences'] = _dict.get('sentences') + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = SyntaxOptionsTokens.from_dict(tokens) + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = sentences return cls(**args) @classmethod @@ -5526,20 +5750,22 @@ def __ne__(self, other: 'SyntaxOptions') -> bool: return not self == other -class SyntaxOptionsTokens(): +class SyntaxOptionsTokens: """ Tokenization options. - :attr bool lemma: (optional) Set this to `true` to return the lemma for each + :param bool lemma: (optional) Set this to `true` to return the lemma for each token. - :attr bool part_of_speech: (optional) Set this to `true` to return the part of + :param bool part_of_speech: (optional) Set this to `true` to return the part of speech for each token. """ - def __init__(self, - *, - lemma: bool = None, - part_of_speech: bool = None) -> None: + def __init__( + self, + *, + lemma: Optional[bool] = None, + part_of_speech: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -5555,10 +5781,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -5594,18 +5820,20 @@ def __ne__(self, other: 'SyntaxOptionsTokens') -> bool: return not self == other -class SyntaxResult(): +class SyntaxResult: """ Tokens and sentences returned from syntax analysis. - :attr List[TokenResult] tokens: (optional) - :attr List[SentenceResult] sentences: (optional) + :param List[TokenResult] tokens: (optional) + :param List[SentenceResult] sentences: (optional) """ - def __init__(self, - *, - tokens: List['TokenResult'] = None, - sentences: List['SentenceResult'] = None) -> None: + def __init__( + self, + *, + tokens: Optional[List['TokenResult']] = None, + sentences: Optional[List['SentenceResult']] = None, + ) -> None: """ Initialize a SyntaxResult object. @@ -5619,14 +5847,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = [ - TokenResult.from_dict(v) for v in _dict.get('tokens') - ] - if 'sentences' in _dict: - args['sentences'] = [ - SentenceResult.from_dict(v) for v in _dict.get('sentences') - ] + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = [TokenResult.from_dict(v) for v in tokens] + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = [SentenceResult.from_dict(v) for v in sentences] return cls(**args) @classmethod @@ -5674,18 +5898,20 @@ def __ne__(self, other: 'SyntaxResult') -> bool: return not self == other -class TargetedEmotionResults(): +class TargetedEmotionResults: """ Emotion results for a specified target. - :attr str text: (optional) Targeted text. - :attr EmotionScores emotion: (optional) The emotion results for the target. + :param str text: (optional) Targeted text. + :param EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, - *, - text: str = None, - emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a TargetedEmotionResults object. @@ -5700,10 +5926,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -5742,16 +5968,21 @@ def __ne__(self, other: 'TargetedEmotionResults') -> bool: return not self == other -class TargetedSentimentResults(): +class TargetedSentimentResults: """ TargetedSentimentResults. - :attr str text: (optional) Targeted text. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param str text: (optional) Targeted text. + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, text: str = None, score: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a TargetedSentimentResults object. @@ -5766,10 +5997,10 @@ def __init__(self, *, text: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -5805,26 +6036,28 @@ def __ne__(self, other: 'TargetedSentimentResults') -> bool: return not self == other -class TokenResult(): +class TokenResult: """ TokenResult. - :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For more + :param str text: (optional) The token as it appears in the analyzed text. + :param str part_of_speech: (optional) The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. - :attr str lemma: (optional) The + :param str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. """ - def __init__(self, - *, - text: str = None, - part_of_speech: str = None, - location: List[int] = None, - lemma: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + part_of_speech: Optional[str] = None, + location: Optional[List[int]] = None, + lemma: Optional[str] = None, + ) -> None: """ Initialize a TokenResult object. @@ -5846,14 +6079,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech + if (location := _dict.get('location')) is not None: + args['location'] = location + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma return cls(**args) @classmethod @@ -5897,6 +6130,7 @@ class PartOfSpeechEnum(str, Enum): The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ + ADJ = 'ADJ' ADP = 'ADP' ADV = 'ADV' diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 7d35d6eb..f6d1022b 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -51,7 +51,7 @@ """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -95,7 +95,10 @@ def __init__( # Models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -112,9 +115,11 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -123,12 +128,20 @@ def list_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a model. @@ -148,9 +161,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -162,7 +177,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -171,35 +190,38 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: # Synchronous ######################### - def recognize(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - grammar_name: str = None, - redaction: bool = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - character_insertion_bias: float = None, - **kwargs) -> DetailedResponse: + def recognize( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[bool] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Recognize audio. @@ -425,6 +447,9 @@ def recognize(self, (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param bool smart_formatting_version: (optional) Smart formatting version + is for next-generation models and that is supported in US English, + Brazilian Portuguese, French and German languages. :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -575,9 +600,11 @@ def recognize(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='recognize') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='recognize', + ) headers.update(sdk_headers) params = { @@ -595,6 +622,7 @@ def recognize(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, @@ -615,11 +643,13 @@ def recognize(self, headers['Accept'] = 'application/json' url = '/v1/recognize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -628,11 +658,13 @@ def recognize(self, # Asynchronous ######################### - def register_callback(self, - callback_url: str, - *, - user_secret: str = None, - **kwargs) -> DetailedResponse: + def register_callback( + self, + callback_url: str, + *, + user_secret: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Register a callback. @@ -685,9 +717,11 @@ def register_callback(self, if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='register_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='register_callback', + ) headers.update(sdk_headers) params = { @@ -701,16 +735,21 @@ def register_callback(self, headers['Accept'] = 'application/json' url = '/v1/register_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def unregister_callback(self, callback_url: str, - **kwargs) -> DetailedResponse: + def unregister_callback( + self, + callback_url: str, + **kwargs, + ) -> DetailedResponse: """ Unregister a callback. @@ -730,9 +769,11 @@ def unregister_callback(self, callback_url: str, if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='unregister_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='unregister_callback', + ) headers.update(sdk_headers) params = { @@ -744,49 +785,54 @@ def unregister_callback(self, callback_url: str, del kwargs['headers'] url = '/v1/unregister_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_job(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - callback_url: str = None, - events: str = None, - user_token: str = None, - results_ttl: int = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - grammar_name: str = None, - redaction: bool = None, - processing_metrics: bool = None, - processing_metrics_interval: float = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - character_insertion_bias: float = None, - **kwargs) -> DetailedResponse: + def create_job( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + callback_url: Optional[str] = None, + events: Optional[str] = None, + user_token: Optional[str] = None, + results_ttl: Optional[int] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[bool] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + processing_metrics: Optional[bool] = None, + processing_metrics_interval: Optional[float] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Create a job. @@ -1060,6 +1106,9 @@ def create_job(self, (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param bool smart_formatting_version: (optional) Smart formatting version + is for next-generation models and that is supported in US English, + Brazilian Portuguese, French and German languages. :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -1232,9 +1281,11 @@ def create_job(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_job', + ) headers.update(sdk_headers) params = { @@ -1256,6 +1307,7 @@ def create_job(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, @@ -1278,16 +1330,21 @@ def create_job(self, headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def check_jobs(self, **kwargs) -> DetailedResponse: + def check_jobs( + self, + **kwargs, + ) -> DetailedResponse: """ Check jobs. @@ -1308,9 +1365,11 @@ def check_jobs(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_jobs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_jobs', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1319,12 +1378,20 @@ def check_jobs(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def check_job(self, id: str, **kwargs) -> DetailedResponse: + def check_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Check a job. @@ -1352,9 +1419,11 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1366,12 +1435,20 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_job(self, id: str, **kwargs) -> DetailedResponse: + def delete_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a job. @@ -1394,9 +1471,11 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1407,9 +1486,11 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1418,13 +1499,15 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: # Custom language models ######################### - def create_language_model(self, - name: str, - base_model_name: str, - *, - dialect: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_language_model( + self, + name: str, + base_model_name: str, + *, + dialect: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom language model. @@ -1493,9 +1576,11 @@ def create_language_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_language_model', + ) headers.update(sdk_headers) data = { @@ -1514,18 +1599,22 @@ def create_language_model(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_language_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_language_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom language models. @@ -1555,9 +1644,11 @@ def list_language_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_language_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_language_models', + ) headers.update(sdk_headers) params = { @@ -1570,16 +1661,21 @@ def list_language_models(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom language model. @@ -1603,9 +1699,11 @@ def get_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1617,13 +1715,20 @@ def get_language_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom language model. @@ -1649,9 +1754,11 @@ def delete_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1663,20 +1770,25 @@ def delete_language_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_language_model(self, - customization_id: str, - *, - word_type_to_add: str = None, - customization_weight: float = None, - strict: bool = None, - **kwargs) -> DetailedResponse: + def train_language_model( + self, + customization_id: str, + *, + word_type_to_add: Optional[str] = None, + customization_weight: Optional[float] = None, + strict: Optional[bool] = None, + force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom language model. @@ -1762,6 +1874,15 @@ def train_language_model(self, lists any invalid resources. By default (`true`), training of a custom language model fails (status code 400) if the model contains one or more invalid resources (corpus files, grammar files, or custom words). + :param bool force: (optional) If `true`, forces the training of the custom + language model regardless of whether it contains any changes (is in the + `ready` or `available` state). By default (`false`), the model must be in + the `ready` state to be trained. You can use the parameter to train and + thus upgrade a custom model that is based on an improved next-generation + model. *The parameter is available only for IBM Cloud, not for IBM Cloud + Pak for Data.* + See [Upgrading a custom language model based on an improved next-generation + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object @@ -1770,15 +1891,18 @@ def train_language_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_language_model', + ) headers.update(sdk_headers) params = { 'word_type_to_add': word_type_to_add, 'customization_weight': customization_weight, 'strict': strict, + 'force': force, } if 'headers' in kwargs: @@ -1791,16 +1915,21 @@ def train_language_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom language model. @@ -1828,9 +1957,11 @@ def reset_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1843,13 +1974,20 @@ def reset_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def upgrade_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom language model. @@ -1892,9 +2030,11 @@ def upgrade_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1907,7 +2047,11 @@ def upgrade_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1916,7 +2060,11 @@ def upgrade_language_model(self, customization_id: str, # Custom corpora ######################### - def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_corpora( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List corpora. @@ -1940,9 +2088,11 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_corpora') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_corpora', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1955,18 +2105,24 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_corpus(self, - customization_id: str, - corpus_name: str, - corpus_file: BinaryIO, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_corpus( + self, + customization_id: str, + corpus_name: str, + corpus_file: BinaryIO, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a corpus. @@ -2067,9 +2223,11 @@ def add_corpus(self, if corpus_file is None: raise ValueError('corpus_file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_corpus', + ) headers.update(sdk_headers) params = { @@ -2089,17 +2247,23 @@ def add_corpus(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def get_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a corpus. @@ -2127,9 +2291,11 @@ def get_corpus(self, customization_id: str, corpus_name: str, if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2142,13 +2308,21 @@ def get_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def delete_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a corpus. @@ -2180,9 +2354,11 @@ def delete_corpus(self, customization_id: str, corpus_name: str, if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2195,9 +2371,11 @@ def delete_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2206,12 +2384,14 @@ def delete_corpus(self, customization_id: str, corpus_name: str, # Custom words ######################### - def list_words(self, - customization_id: str, - *, - word_type: str = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + *, + word_type: Optional[str] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -2260,9 +2440,11 @@ def list_words(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) params = { @@ -2280,16 +2462,22 @@ def list_words(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_words(self, customization_id: str, words: List['CustomWord'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['CustomWord'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -2324,6 +2512,13 @@ def add_words(self, customization_id: str, words: List['CustomWord'], omit the `sounds_like` field, the service attempts to set the field to its pronunciation of the word. It cannot generate a pronunciation for all words, so you must review the word's definition to ensure that it is complete and valid. + * The `mapping_only` field provides parameter for custom words. You can use the + 'mapping_only' key in custom words as a form of post processing. This key + parameter has a boolean value to determine whether 'sounds_like' (for non-Japanese + models) or word (for Japanese) is not used for the model fine-tuning, but for the + replacement for 'display_as'. This feature helps you when you use custom words + exclusively to map 'sounds_like' (or word) to 'display_as' value. When you use + custom words solely for post-processing purposes that does not need fine-tuning. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2373,9 +2568,11 @@ def add_words(self, customization_id: str, words: List['CustomWord'], raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) data = { @@ -2395,22 +2592,27 @@ def add_words(self, customization_id: str, words: List['CustomWord'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word_name: str, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word_name: str, + *, + word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -2465,16 +2667,30 @@ def add_word(self, request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be added to or updated in - the custom language model. Do not include spaces in the word. Use a `-` + the custom language model. Do not use characters that need to be + URL-encoded, for example, spaces, slashes, backslashes, colons, ampersands, + double quotes, plus signs, equals signs, or question marks. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. URL-encode the word if it includes non-ASCII characters. For more information, see [Character encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the - custom model. Do not include spaces in the word. Use a `-` (dash) or `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. @@ -2487,7 +2703,9 @@ def add_word(self, default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -2505,13 +2723,16 @@ def add_word(self, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) data = { 'word': word, + 'mapping_only': mapping_only, 'sounds_like': sounds_like, 'display_as': display_as, } @@ -2529,16 +2750,22 @@ def add_word(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -2566,9 +2793,11 @@ def get_word(self, customization_id: str, word_name: str, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2581,13 +2810,21 @@ def get_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -2619,9 +2856,11 @@ def delete_word(self, customization_id: str, word_name: str, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2634,9 +2873,11 @@ def delete_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2645,8 +2886,11 @@ def delete_word(self, customization_id: str, word_name: str, # Custom grammars ######################### - def list_grammars(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_grammars( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List grammars. @@ -2673,9 +2917,11 @@ def list_grammars(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_grammars') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_grammars', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2688,19 +2934,25 @@ def list_grammars(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_grammar(self, - customization_id: str, - grammar_name: str, - grammar_file: BinaryIO, - content_type: str, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_grammar( + self, + customization_id: str, + grammar_name: str, + grammar_file: BinaryIO, + content_type: str, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a grammar. @@ -2797,9 +3049,11 @@ def add_grammar(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_grammar', + ) headers.update(sdk_headers) params = { @@ -2819,17 +3073,23 @@ def add_grammar(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def get_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a grammar. @@ -2860,9 +3120,11 @@ def get_grammar(self, customization_id: str, grammar_name: str, if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2876,13 +3138,21 @@ def get_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def delete_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a grammar. @@ -2917,9 +3187,11 @@ def delete_grammar(self, customization_id: str, grammar_name: str, if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2933,9 +3205,11 @@ def delete_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2944,12 +3218,14 @@ def delete_grammar(self, customization_id: str, grammar_name: str, # Custom acoustic models ######################### - def create_acoustic_model(self, - name: str, - base_model_name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def create_acoustic_model( + self, + name: str, + base_model_name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom acoustic model. @@ -2999,9 +3275,11 @@ def create_acoustic_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_acoustic_model', + ) headers.update(sdk_headers) data = { @@ -3019,18 +3297,22 @@ def create_acoustic_model(self, headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_acoustic_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_acoustic_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom acoustic models. @@ -3059,9 +3341,11 @@ def list_acoustic_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_acoustic_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_acoustic_models', + ) headers.update(sdk_headers) params = { @@ -3074,16 +3358,21 @@ def list_acoustic_models(self, headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom acoustic model. @@ -3106,9 +3395,11 @@ def get_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3121,13 +3412,20 @@ def get_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom acoustic model. @@ -3152,9 +3450,11 @@ def delete_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3167,19 +3467,23 @@ def delete_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - strict: bool = None, - **kwargs) -> DetailedResponse: + def train_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + strict: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom acoustic model. @@ -3269,9 +3573,11 @@ def train_acoustic_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_acoustic_model', + ) headers.update(sdk_headers) params = { @@ -3289,16 +3595,21 @@ def train_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom acoustic model. @@ -3327,9 +3638,11 @@ def reset_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3342,17 +3655,23 @@ def reset_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - force: bool = None, - **kwargs) -> DetailedResponse: + def upgrade_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom acoustic model. @@ -3408,9 +3727,11 @@ def upgrade_acoustic_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_acoustic_model', + ) headers.update(sdk_headers) params = { @@ -3428,10 +3749,12 @@ def upgrade_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3440,7 +3763,11 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_audio( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List audio resources. @@ -3467,9 +3794,11 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3482,20 +3811,26 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_audio(self, - customization_id: str, - audio_name: str, - audio_resource: BinaryIO, - *, - content_type: str = None, - contained_content_type: str = None, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_audio( + self, + customization_id: str, + audio_name: str, + audio_resource: BinaryIO, + *, + content_type: Optional[str] = None, + contained_content_type: Optional[str] = None, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add an audio resource. @@ -3649,9 +3984,11 @@ def add_audio(self, 'Content-Type': content_type, 'Contained-Content-Type': contained_content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_audio', + ) headers.update(sdk_headers) params = { @@ -3670,17 +4007,23 @@ def add_audio(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def get_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Get an audio resource. @@ -3723,9 +4066,11 @@ def get_audio(self, customization_id: str, audio_name: str, if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3738,13 +4083,21 @@ def get_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def delete_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete an audio resource. @@ -3778,9 +4131,11 @@ def delete_audio(self, customization_id: str, audio_name: str, if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3793,9 +4148,11 @@ def delete_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -3804,7 +4161,11 @@ def delete_audio(self, customization_id: str, audio_name: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3833,9 +4194,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3847,10 +4210,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3866,6 +4231,7 @@ class ModelId(str, Enum): The identifier of the model in the form of its name from the output of the [List models](#listmodels) method. """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3949,6 +4315,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -3979,6 +4346,7 @@ class Model(str, Enum): * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -4062,6 +4430,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -4092,6 +4461,7 @@ class Model(str, Enum): * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -4184,6 +4554,7 @@ class Events(str, Enum): `recognitions.failed`. If the job does not include a callback URL, omit the parameter. """ + RECOGNITIONS_STARTED = 'recognitions.started' RECOGNITIONS_COMPLETED = 'recognitions.completed' RECOGNITIONS_COMPLETED_WITH_RESULTS = 'recognitions.completed_with_results' @@ -4206,6 +4577,7 @@ class Language(str, Enum): support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4253,6 +4625,7 @@ class WordTypeToAdd(str, Enum): the parameter. The words resource contains only custom words that the user adds or modifies directly, so the parameter is unnecessary. """ + ALL = 'all' USER = 'user' @@ -4273,6 +4646,7 @@ class WordType(str, Enum): `user` apply. Both options return the same results. Words from other sources are not added to custom models that are based on next-generation models. """ + ALL = 'all' USER = 'user' CORPORA = 'corpora' @@ -4288,6 +4662,7 @@ class Sort(str, Enum): letters. For count ordering, values with the same count are ordered alphabetically. With the `curl` command, URL-encode the `+` symbol as `%2B`. """ + ALPHABETICAL = 'alphabetical' COUNT = 'count' @@ -4305,6 +4680,7 @@ class ContentType(str, Enum): * `application/srgs+xml` for XML Form, which uses XML elements to represent the grammar. """ + APPLICATION_SRGS = 'application/srgs' APPLICATION_SRGS_XML = 'application/srgs+xml' @@ -4325,6 +4701,7 @@ class Language(str, Enum): support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4367,6 +4744,7 @@ class ContentType(str, Enum): information, see **Content types for archive-type resources** in the method description. """ + APPLICATION_ZIP = 'application/zip' APPLICATION_GZIP = 'application/gzip' AUDIO_ALAW = 'audio/alaw' @@ -4400,6 +4778,7 @@ class ContainedContentType(str, Enum): resources** in the method description. _For an audio-type resource_, omit the header. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' @@ -4422,35 +4801,35 @@ class ContainedContentType(str, Enum): ############################################################################## -class AcousticModel(): +class AcousticModel: """ Information about an existing custom acoustic model. - :attr str customization_id: The customization ID (GUID) of the custom acoustic + :param str customization_id: The customization ID (GUID) of the custom acoustic model. The [Create a custom acoustic model](#createacousticmodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was last modified. The `created` and `updated` fields are equal when an acoustic model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom acoustic + :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. - :attr str name: (optional) The name of the custom acoustic model. - :attr str description: (optional) The description of the custom acoustic model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom acoustic model. + :param str description: (optional) The description of the custom acoustic model. + :param str base_model_name: (optional) The name of the language model for which the custom acoustic model was created. - :attr str status: (optional) The current status of the custom acoustic model: + :param str status: (optional) The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -4460,31 +4839,33 @@ class AcousticModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom acoustic model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a AcousticModel object. @@ -4552,34 +4933,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in AcousticModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -4649,6 +5030,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -4657,18 +5039,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class AcousticModels(): +class AcousticModels: """ Information about existing custom acoustic models. - :attr List[AcousticModel] customizations: An array of `AcousticModel` objects + :param List[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ - def __init__(self, customizations: List['AcousticModel']) -> None: + def __init__( + self, + customizations: List['AcousticModel'], + ) -> None: """ Initialize a AcousticModels object. @@ -4684,9 +5069,9 @@ def __init__(self, customizations: List['AcousticModel']) -> None: def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - AcousticModel.from_dict(v) for v in _dict.get('customizations') + AcousticModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -4731,35 +5116,37 @@ def __ne__(self, other: 'AcousticModels') -> bool: return not self == other -class AudioDetails(): +class AudioDetails: """ Information about an audio resource from a custom acoustic model. - :attr str type: (optional) The type of the audio resource: + :param str type: (optional) The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). - :attr str codec: (optional) _For an audio-type resource_, the codec in which the - audio is encoded. Omitted for an archive-type resource. - :attr int frequency: (optional) _For an audio-type resource_, the sampling rate + :param str codec: (optional) _For an audio-type resource_, the codec in which + the audio is encoded. Omitted for an archive-type resource. + :param int frequency: (optional) _For an audio-type resource_, the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :attr str compression: (optional) _For an archive-type resource_, the format of + :param str compression: (optional) _For an archive-type resource_, the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ - def __init__(self, - *, - type: str = None, - codec: str = None, - frequency: int = None, - compression: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + codec: Optional[str] = None, + frequency: Optional[int] = None, + compression: Optional[str] = None, + ) -> None: """ Initialize a AudioDetails object. @@ -4790,14 +5177,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'codec' in _dict: - args['codec'] = _dict.get('codec') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') - if 'compression' in _dict: - args['compression'] = _dict.get('compression') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (codec := _dict.get('codec')) is not None: + args['codec'] = codec + if (frequency := _dict.get('frequency')) is not None: + args['frequency'] = frequency + if (compression := _dict.get('compression')) is not None: + args['compression'] = compression return cls(**args) @classmethod @@ -4846,6 +5233,7 @@ class TypeEnum(str, Enum): the user mistakenly passes a file that does not contain audio, such as a JPEG file). """ + AUDIO = 'audio' ARCHIVE = 'archive' UNDETERMINED = 'undetermined' @@ -4857,23 +5245,24 @@ class CompressionEnum(str, Enum): * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ + ZIP = 'zip' GZIP = 'gzip' -class AudioListing(): +class AudioListing: """ Information about an audio resource from a custom acoustic model. - :attr int duration: (optional) _For an audio-type resource_, the total seconds + :param int duration: (optional) _For an audio-type resource_, the total seconds of audio in the resource. Omitted for an archive-type resource. - :attr str name: (optional) _For an audio-type resource_, the user-specified name - of the resource. Omitted for an archive-type resource. - :attr AudioDetails details: (optional) _For an audio-type resource_, an + :param str name: (optional) _For an audio-type resource_, the user-specified + name of the resource. Omitted for an archive-type resource. + :param AudioDetails details: (optional) _For an audio-type resource_, an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. - :attr str status: (optional) _For an audio-type resource_, the status of the + :param str status: (optional) _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. @@ -4883,23 +5272,25 @@ class AudioListing(): * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. - :attr AudioResource container: (optional) _For an archive-type resource_, an + :param AudioResource container: (optional) _For an archive-type resource_, an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :attr List[AudioResource] audio: (optional) _For an archive-type resource_, an + :param List[AudioResource] audio: (optional) _For an archive-type resource_, an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ - def __init__(self, - *, - duration: int = None, - name: str = None, - details: 'AudioDetails' = None, - status: str = None, - container: 'AudioResource' = None, - audio: List['AudioResource'] = None) -> None: + def __init__( + self, + *, + duration: Optional[int] = None, + name: Optional[str] = None, + details: Optional['AudioDetails'] = None, + status: Optional[str] = None, + container: Optional['AudioResource'] = None, + audio: Optional[List['AudioResource']] = None, + ) -> None: """ Initialize a AudioListing object. @@ -4941,20 +5332,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'container' in _dict: - args['container'] = AudioResource.from_dict(_dict.get('container')) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(v) for v in _dict.get('audio') - ] + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration + if (name := _dict.get('name')) is not None: + args['name'] = name + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (container := _dict.get('container')) is not None: + args['container'] = AudioResource.from_dict(container) + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] return cls(**args) @classmethod @@ -5021,27 +5410,31 @@ class StatusEnum(str, Enum): because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioMetrics(): +class AudioMetrics: """ If audio metrics are requested, information about the signal characteristics of the input audio. - :attr float sampling_interval: The interval in seconds (typically 0.1 seconds) + :param float sampling_interval: The interval in seconds (typically 0.1 seconds) at which the service calculated the audio metrics. In other words, how often the service calculated the metrics. A single unit in each histogram (see the `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` length of audio. - :attr AudioMetricsDetails accumulated: Detailed information about the signal + :param AudioMetricsDetails accumulated: Detailed information about the signal characteristics of the input audio. """ - def __init__(self, sampling_interval: float, - accumulated: 'AudioMetricsDetails') -> None: + def __init__( + self, + sampling_interval: float, + accumulated: 'AudioMetricsDetails', + ) -> None: """ Initialize a AudioMetrics object. @@ -5060,15 +5453,14 @@ def __init__(self, sampling_interval: float, def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} - if 'sampling_interval' in _dict: - args['sampling_interval'] = _dict.get('sampling_interval') + if (sampling_interval := _dict.get('sampling_interval')) is not None: + args['sampling_interval'] = sampling_interval else: raise ValueError( 'Required property \'sampling_interval\' not present in AudioMetrics JSON' ) - if 'accumulated' in _dict: - args['accumulated'] = AudioMetricsDetails.from_dict( - _dict.get('accumulated')) + if (accumulated := _dict.get('accumulated')) is not None: + args['accumulated'] = AudioMetricsDetails.from_dict(accumulated) else: raise ValueError( 'Required property \'accumulated\' not present in AudioMetrics JSON' @@ -5112,23 +5504,23 @@ def __ne__(self, other: 'AudioMetrics') -> bool: return not self == other -class AudioMetricsDetails(): +class AudioMetricsDetails: """ Detailed information about the signal characteristics of the input audio. - :attr bool final: If `true`, indicates the end of the audio stream, meaning that - transcription is complete. Currently, the field is always `true`. The service - returns metrics just once per audio stream. The results provide aggregated audio - metrics that pertain to the complete audio stream. - :attr float end_time: The end time in seconds of the block of audio to which the - metrics apply. - :attr float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) + :param bool final: If `true`, indicates the end of the audio stream, meaning + that transcription is complete. Currently, the field is always `true`. The + service returns metrics just once per audio stream. The results provide + aggregated audio metrics that pertain to the complete audio stream. + :param float end_time: The end time in seconds of the block of audio to which + the metrics apply. + :param float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) for the audio signal. The value indicates the ratio of speech to noise in the audio. A valid value lies in the range of 0 to 100 decibels (dB). The service omits the field if it cannot compute the SNR for the audio. - :attr float speech_ratio: The ratio of speech to non-speech segments in the + :param float speech_ratio: The ratio of speech to non-speech segments in the audio signal. The value lies in the range of 0.0 to 1.0. - :attr float high_frequency_loss: The probability that the audio signal is + :param float high_frequency_loss: The probability that the audio signal is missing the upper half of its frequency content. * A value close to 1.0 typically indicates artificially up-sampled audio, which negatively impacts the accuracy of the transcription results. @@ -5136,10 +5528,10 @@ class AudioMetricsDetails(): spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :attr List[AudioMetricsHistogramBin] direct_current_offset: An array of + :param List[AudioMetricsHistogramBin] direct_current_offset: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct current (DC) component of the audio signal. - :attr List[AudioMetricsHistogramBin] clipping_rate: An array of + :param List[AudioMetricsHistogramBin] clipping_rate: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for the audio segments. The clipping rate is defined as the fraction of samples in the segment that reach the maximum or minimum value that is offered by the @@ -5147,29 +5539,31 @@ class AudioMetricsDetails(): Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher values indicating possible degradation of speech recognition. - :attr List[AudioMetricsHistogramBin] speech_level: An array of + :param List[AudioMetricsHistogramBin] speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). - :attr List[AudioMetricsHistogramBin] non_speech_level: An array of + :param List[AudioMetricsHistogramBin] non_speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that do not contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). """ - def __init__(self, - final: bool, - end_time: float, - speech_ratio: float, - high_frequency_loss: float, - direct_current_offset: List['AudioMetricsHistogramBin'], - clipping_rate: List['AudioMetricsHistogramBin'], - speech_level: List['AudioMetricsHistogramBin'], - non_speech_level: List['AudioMetricsHistogramBin'], - *, - signal_to_noise_ratio: float = None) -> None: + def __init__( + self, + final: bool, + end_time: float, + speech_ratio: float, + high_frequency_loss: float, + direct_current_offset: List['AudioMetricsHistogramBin'], + clipping_rate: List['AudioMetricsHistogramBin'], + speech_level: List['AudioMetricsHistogramBin'], + non_speech_level: List['AudioMetricsHistogramBin'], + *, + signal_to_noise_ratio: Optional[float] = None, + ) -> None: """ Initialize a AudioMetricsDetails object. @@ -5230,63 +5624,63 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in AudioMetricsDetails JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in AudioMetricsDetails JSON' ) - if 'signal_to_noise_ratio' in _dict: - args['signal_to_noise_ratio'] = _dict.get('signal_to_noise_ratio') - if 'speech_ratio' in _dict: - args['speech_ratio'] = _dict.get('speech_ratio') + if (signal_to_noise_ratio := + _dict.get('signal_to_noise_ratio')) is not None: + args['signal_to_noise_ratio'] = signal_to_noise_ratio + if (speech_ratio := _dict.get('speech_ratio')) is not None: + args['speech_ratio'] = speech_ratio else: raise ValueError( 'Required property \'speech_ratio\' not present in AudioMetricsDetails JSON' ) - if 'high_frequency_loss' in _dict: - args['high_frequency_loss'] = _dict.get('high_frequency_loss') + if (high_frequency_loss := + _dict.get('high_frequency_loss')) is not None: + args['high_frequency_loss'] = high_frequency_loss else: raise ValueError( 'Required property \'high_frequency_loss\' not present in AudioMetricsDetails JSON' ) - if 'direct_current_offset' in _dict: + if (direct_current_offset := + _dict.get('direct_current_offset')) is not None: args['direct_current_offset'] = [ AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('direct_current_offset') + for v in direct_current_offset ] else: raise ValueError( 'Required property \'direct_current_offset\' not present in AudioMetricsDetails JSON' ) - if 'clipping_rate' in _dict: + if (clipping_rate := _dict.get('clipping_rate')) is not None: args['clipping_rate'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('clipping_rate') + AudioMetricsHistogramBin.from_dict(v) for v in clipping_rate ] else: raise ValueError( 'Required property \'clipping_rate\' not present in AudioMetricsDetails JSON' ) - if 'speech_level' in _dict: + if (speech_level := _dict.get('speech_level')) is not None: args['speech_level'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in speech_level ] else: raise ValueError( 'Required property \'speech_level\' not present in AudioMetricsDetails JSON' ) - if 'non_speech_level' in _dict: + if (non_speech_level := _dict.get('non_speech_level')) is not None: args['non_speech_level'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('non_speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in non_speech_level ] else: raise ValueError( @@ -5370,19 +5764,24 @@ def __ne__(self, other: 'AudioMetricsDetails') -> bool: return not self == other -class AudioMetricsHistogramBin(): +class AudioMetricsHistogramBin: """ A bin with defined boundaries that indicates the number of values in a range of signal characteristics for a histogram. The first and last bins of a histogram are the boundary bins. They cover the intervals between negative infinity and the first boundary, and between the last boundary and positive infinity, respectively. - :attr float begin: The lower boundary of the bin in the histogram. - :attr float end: The upper boundary of the bin in the histogram. - :attr int count: The number of values in the bin of the histogram. + :param float begin: The lower boundary of the bin in the histogram. + :param float end: The upper boundary of the bin in the histogram. + :param int count: The number of values in the bin of the histogram. """ - def __init__(self, begin: float, end: float, count: int) -> None: + def __init__( + self, + begin: float, + end: float, + count: int, + ) -> None: """ Initialize a AudioMetricsHistogramBin object. @@ -5398,20 +5797,20 @@ def __init__(self, begin: float, end: float, count: int) -> None: def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in AudioMetricsHistogramBin JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in AudioMetricsHistogramBin JSON' ) - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in AudioMetricsHistogramBin JSON' @@ -5453,20 +5852,20 @@ def __ne__(self, other: 'AudioMetricsHistogramBin') -> bool: return not self == other -class AudioResource(): +class AudioResource: """ Information about an audio resource from a custom acoustic model. - :attr int duration: The total seconds of audio in the audio resource. - :attr str name: _For an archive-type resource_, the user-specified name of the + :param int duration: The total seconds of audio in the audio resource. + :param str name: _For an archive-type resource_, the user-specified name of the resource. _For an audio-type resource_, the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. - :attr AudioDetails details: An `AudioDetails` object that provides detailed + :param AudioDetails details: An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the service finishes processing the audio. - :attr str status: The status of the audio resource: + :param str status: The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service @@ -5478,8 +5877,13 @@ class AudioResource(): invalid. """ - def __init__(self, duration: int, name: str, details: 'AudioDetails', - status: str) -> None: + def __init__( + self, + duration: int, + name: str, + details: 'AudioDetails', + status: str, + ) -> None: """ Initialize a AudioResource object. @@ -5512,25 +5916,25 @@ def __init__(self, duration: int, name: str, details: 'AudioDetails', def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration else: raise ValueError( 'Required property \'duration\' not present in AudioResource JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in AudioResource JSON') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) else: raise ValueError( 'Required property \'details\' not present in AudioResource JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in AudioResource JSON' @@ -5589,26 +5993,30 @@ class StatusEnum(str, Enum): an archive file, the entire archive is invalid if any of its audio files are invalid. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioResources(): +class AudioResources: """ Information about the audio resources from a custom acoustic model. - :attr float total_minutes_of_audio: The total minutes of accumulated audio + :param float total_minutes_of_audio: The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. - :attr List[AudioResource] audio: An array of `AudioResource` objects that + :param List[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ - def __init__(self, total_minutes_of_audio: float, - audio: List['AudioResource']) -> None: + def __init__( + self, + total_minutes_of_audio: float, + audio: List['AudioResource'], + ) -> None: """ Initialize a AudioResources object. @@ -5627,16 +6035,15 @@ def __init__(self, total_minutes_of_audio: float, def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} - if 'total_minutes_of_audio' in _dict: - args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') + if (total_minutes_of_audio := + _dict.get('total_minutes_of_audio')) is not None: + args['total_minutes_of_audio'] = total_minutes_of_audio else: raise ValueError( 'Required property \'total_minutes_of_audio\' not present in AudioResources JSON' ) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(v) for v in _dict.get('audio') - ] + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] else: raise ValueError( 'Required property \'audio\' not present in AudioResources JSON' @@ -5683,16 +6090,19 @@ def __ne__(self, other: 'AudioResources') -> bool: return not self == other -class Corpora(): +class Corpora: """ Information about the corpora from a custom language model. - :attr List[Corpus] corpora: An array of `Corpus` objects that provides + :param List[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ - def __init__(self, corpora: List['Corpus']) -> None: + def __init__( + self, + corpora: List['Corpus'], + ) -> None: """ Initialize a Corpora object. @@ -5706,10 +6116,8 @@ def __init__(self, corpora: List['Corpus']) -> None: def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} - if 'corpora' in _dict: - args['corpora'] = [ - Corpus.from_dict(v) for v in _dict.get('corpora') - ] + if (corpora := _dict.get('corpora')) is not None: + args['corpora'] = [Corpus.from_dict(v) for v in corpora] else: raise ValueError( 'Required property \'corpora\' not present in Corpora JSON') @@ -5752,37 +6160,39 @@ def __ne__(self, other: 'Corpora') -> bool: return not self == other -class Corpus(): +class Corpus: """ Information about a corpus from a custom language model. - :attr str name: The name of the corpus. - :attr int total_words: The total number of words in the corpus. The value is `0` - while the corpus is being processed. - :attr int out_of_vocabulary_words: _For custom models that are based on + :param str name: The name of the corpus. + :param int total_words: The total number of words in the corpus. The value is + `0` while the corpus is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on previous-generation models_, the number of OOV words extracted from the corpus. The value is `0` while the corpus is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. - :attr str status: The status of the corpus: + :param str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. * `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. - :attr str error: (optional) If the status of the corpus is `undetermined`, the + :param str error: (optional) If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ - def __init__(self, - name: str, - total_words: int, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + total_words: int, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Corpus object. @@ -5815,30 +6225,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Corpus JSON') - if 'total_words' in _dict: - args['total_words'] = _dict.get('total_words') + if (total_words := _dict.get('total_words')) is not None: + args['total_words'] = total_words else: raise ValueError( 'Required property \'total_words\' not present in Corpus JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Corpus JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Corpus JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -5890,21 +6300,33 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class CustomWord(): +class CustomWord: """ Information about a word that is to be added to a custom language model. - :attr str word: (optional) For the [Add custom words](#addwords) method, you + :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the custom - model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) - to connect the tokens of compound words. + model. Do not use characters that need to be URL-encoded, for example, spaces, + slashes, backslashes, colons, ampersands, double quotes, plus signs, equals + signs, or question marks. Use a `-` (dash) or `_` (underscore) to connect the + tokens of compound words. A Japanese custom word can include at most 25 + characters, not including leading or trailing spaces. Omit this parameter for the [Add a custom word](#addword) method. - :attr List[str] sounds_like: (optional) As array of sounds-like pronunciations + :param List[str] mapping_only: (optional) Parameter for custom words. You can + use the 'mapping_only' key in custom words as a form of post processing. This + key parameter has a boolean value to determine whether 'sounds_like' (for + non-Japanese models) or word (for Japanese) is not used for the model + fine-tuning, but for the replacement for 'display_as'. This feature helps you + when you use custom words exclusively to map 'sounds_like' (or word) to + 'display_as' value. When you use custom words solely for post-processing + purposes that does not need fine-tuning. + :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * _For custom models that are based on previous-generation models_, for a word @@ -5915,8 +6337,10 @@ class CustomWord(): pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can - include at most 40 characters not including spaces. - :attr str display_as: (optional) An alternative spelling for the custom word + include at most 40 characters, not including leading or trailing spaces. A + Japanese pronunciation can include at most 25 characters, not including leading + or trailing spaces. + :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. @@ -5924,19 +6348,34 @@ class CustomWord(): the spelling of the word as the display-as value if you omit the field. """ - def __init__(self, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None) -> None: + def __init__( + self, + *, + word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + ) -> None: """ Initialize a CustomWord object. :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the - custom model. Do not include spaces in the word. Use a `-` (dash) or `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. @@ -5949,7 +6388,9 @@ def __init__(self, default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -5959,6 +6400,7 @@ def __init__(self, field. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as @@ -5966,12 +6408,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (word := _dict.get('word')) is not None: + args['word'] = word + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as return cls(**args) @classmethod @@ -5984,6 +6428,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: @@ -6009,35 +6455,37 @@ def __ne__(self, other: 'CustomWord') -> bool: return not self == other -class Grammar(): +class Grammar: """ Information about a grammar from a custom language model. - :attr str name: The name of the grammar. - :attr int out_of_vocabulary_words: _For custom models that are based on + :param str name: The name of the grammar. + :param int out_of_vocabulary_words: _For custom models that are based on previous-generation models_, the number of OOV words extracted from the grammar. The value is `0` while the grammar is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from grammars, so the value is always `0`. - :attr str status: The status of the grammar: + :param str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. * `being_processed`: The service is still analyzing the grammar. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. - :attr str error: (optional) If the status of the grammar is `undetermined`, the + :param str error: (optional) If the status of the grammar is `undetermined`, the following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. """ - def __init__(self, - name: str, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Grammar object. @@ -6069,25 +6517,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Grammar JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Grammar JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Grammar JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -6137,21 +6585,25 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class Grammars(): +class Grammars: """ Information about the grammars from a custom language model. - :attr List[Grammar] grammars: An array of `Grammar` objects that provides + :param List[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ - def __init__(self, grammars: List['Grammar']) -> None: + def __init__( + self, + grammars: List['Grammar'], + ) -> None: """ Initialize a Grammars object. @@ -6165,10 +6617,8 @@ def __init__(self, grammars: List['Grammar']) -> None: def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} - if 'grammars' in _dict: - args['grammars'] = [ - Grammar.from_dict(v) for v in _dict.get('grammars') - ] + if (grammars := _dict.get('grammars')) is not None: + args['grammars'] = [Grammar.from_dict(v) for v in grammars] else: raise ValueError( 'Required property \'grammars\' not present in Grammars JSON') @@ -6211,20 +6661,25 @@ def __ne__(self, other: 'Grammars') -> bool: return not self == other -class KeywordResult(): +class KeywordResult: """ Information about a match for a keyword from speech recognition results. - :attr str normalized_text: A specified keyword normalized to the spoken phrase + :param str normalized_text: A specified keyword normalized to the spoken phrase that matched in the audio input. - :attr float start_time: The start time in seconds of the keyword match. - :attr float end_time: The end time in seconds of the keyword match. - :attr float confidence: A confidence score for the keyword match in the range of - 0.0 to 1.0. + :param float start_time: The start time in seconds of the keyword match. + :param float end_time: The end time in seconds of the keyword match. + :param float confidence: A confidence score for the keyword match in the range + of 0.0 to 1.0. """ - def __init__(self, normalized_text: str, start_time: float, end_time: float, - confidence: float) -> None: + def __init__( + self, + normalized_text: str, + start_time: float, + end_time: float, + confidence: float, + ) -> None: """ Initialize a KeywordResult object. @@ -6244,26 +6699,26 @@ def __init__(self, normalized_text: str, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} - if 'normalized_text' in _dict: - args['normalized_text'] = _dict.get('normalized_text') + if (normalized_text := _dict.get('normalized_text')) is not None: + args['normalized_text'] = normalized_text else: raise ValueError( 'Required property \'normalized_text\' not present in KeywordResult JSON' ) - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in KeywordResult JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in KeywordResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in KeywordResult JSON' @@ -6308,26 +6763,26 @@ def __ne__(self, other: 'KeywordResult') -> bool: return not self == other -class LanguageModel(): +class LanguageModel: """ Information about an existing custom language model. - :attr str customization_id: The customization ID (GUID) of the custom language + :param str customization_id: The customization ID (GUID) of the custom language model. The [Create a custom language model](#createlanguagemodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was last modified. The `created` and `updated` fields are equal when a language model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom language + :param str language: (optional) The language identifier of the custom language model (for example, `en-US`). The value matches the five-character language identifier from the name of the base model for the custom model. This value might be different from the value of the `dialect` field. - :attr str dialect: (optional) The dialect of the language for the custom + :param str dialect: (optional) The dialect of the language for the custom language model. _For custom models that are based on non-Spanish previous-generation models and on next-generation models,_ the field matches the language of the base model; for example, `en-US` for one of the US English @@ -6340,18 +6795,18 @@ class LanguageModel(): models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. - :attr str name: (optional) The name of the custom language model. - :attr str description: (optional) The description of the custom language model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom language model. + :param str description: (optional) The description of the custom language model. + :param str base_model_name: (optional) The name of the language model for which the custom language model was created. - :attr str status: (optional) The current status of the custom language model: + :param str status: (optional) The current status of the custom language model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -6361,37 +6816,39 @@ class LanguageModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom language model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str error: (optional) If an error occurred while adding a grammar file to + :param str error: (optional) If an error occurred while adding a grammar file to the custom language model, a message that describes an `Internal Server Error` and includes the string `Cannot compile grammar`. The status of the custom model is not affected by the error, but the grammar cannot be used with the model. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - dialect: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - error: str = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + dialect: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + error: Optional[str] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a LanguageModel object. @@ -6481,38 +6938,38 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in LanguageModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'dialect' in _dict: - args['dialect'] = _dict.get('dialect') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (dialect := _dict.get('dialect')) is not None: + args['dialect'] = dialect + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (error := _dict.get('error')) is not None: + args['error'] = error + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -6586,6 +7043,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -6594,18 +7052,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class LanguageModels(): +class LanguageModels: """ Information about existing custom language models. - :attr List[LanguageModel] customizations: An array of `LanguageModel` objects + :param List[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ - def __init__(self, customizations: List['LanguageModel']) -> None: + def __init__( + self, + customizations: List['LanguageModel'], + ) -> None: """ Initialize a LanguageModels object. @@ -6621,9 +7082,9 @@ def __init__(self, customizations: List['LanguageModel']) -> None: def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - LanguageModel.from_dict(v) for v in _dict.get('customizations') + LanguageModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -6668,38 +7129,40 @@ def __ne__(self, other: 'LanguageModels') -> bool: return not self == other -class ProcessedAudio(): +class ProcessedAudio: """ Detailed timing information about the service's processing of the input audio. - :attr float received: The seconds of audio that the service has received as of + :param float received: The seconds of audio that the service has received as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing, since the service first has to receive the audio before it can begin to process it. The final value can also be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float seen_by_engine: The seconds of audio that the service has passed to + :param float seen_by_engine: The seconds of audio that the service has passed to its speech-processing engine as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing. The `received` and `seen_by_engine` fields have identical values when the service has finished processing all audio. This final value can be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float transcription: The seconds of audio that the service has processed + :param float transcription: The seconds of audio that the service has processed for speech recognition as of this response. - :attr float speaker_labels: (optional) If speaker labels are requested, the + :param float speaker_labels: (optional) If speaker labels are requested, the seconds of audio that the service has processed to determine speaker labels as of this response. This value often trails the value of the `transcription` field during speech recognition processing. The `transcription` and `speaker_labels` fields have identical values when the service has finished processing all audio. """ - def __init__(self, - received: float, - seen_by_engine: float, - transcription: float, - *, - speaker_labels: float = None) -> None: + def __init__( + self, + received: float, + seen_by_engine: float, + transcription: float, + *, + speaker_labels: Optional[float] = None, + ) -> None: """ Initialize a ProcessedAudio object. @@ -6736,26 +7199,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} - if 'received' in _dict: - args['received'] = _dict.get('received') + if (received := _dict.get('received')) is not None: + args['received'] = received else: raise ValueError( 'Required property \'received\' not present in ProcessedAudio JSON' ) - if 'seen_by_engine' in _dict: - args['seen_by_engine'] = _dict.get('seen_by_engine') + if (seen_by_engine := _dict.get('seen_by_engine')) is not None: + args['seen_by_engine'] = seen_by_engine else: raise ValueError( 'Required property \'seen_by_engine\' not present in ProcessedAudio JSON' ) - if 'transcription' in _dict: - args['transcription'] = _dict.get('transcription') + if (transcription := _dict.get('transcription')) is not None: + args['transcription'] = transcription else: raise ValueError( 'Required property \'transcription\' not present in ProcessedAudio JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels return cls(**args) @classmethod @@ -6795,15 +7258,15 @@ def __ne__(self, other: 'ProcessedAudio') -> bool: return not self == other -class ProcessingMetrics(): +class ProcessingMetrics: """ If processing metrics are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr ProcessedAudio processed_audio: Detailed timing information about the + :param ProcessedAudio processed_audio: Detailed timing information about the service's processing of the input audio. - :attr float wall_clock_since_first_byte_received: The amount of real time in + :param float wall_clock_since_first_byte_received: The amount of real time in seconds that has passed since the service received the first byte of input audio. Values in this field are generally multiples of the specified metrics interval, with two differences: @@ -6813,7 +7276,7 @@ class ProcessingMetrics(): * The service also returns values for transcription events if you set the `interim_results` parameter to `true`. The service returns both processing metrics and transcription results when such events occur. - :attr bool periodic: An indication of whether the metrics apply to a periodic + :param bool periodic: An indication of whether the metrics apply to a periodic interval or a transcription event: * `true` means that the response was triggered by a specified processing interval. The information contains processing metrics only. @@ -6823,9 +7286,12 @@ class ProcessingMetrics(): different results if necessary. """ - def __init__(self, processed_audio: 'ProcessedAudio', - wall_clock_since_first_byte_received: float, - periodic: bool) -> None: + def __init__( + self, + processed_audio: 'ProcessedAudio', + wall_clock_since_first_byte_received: float, + periodic: bool, + ) -> None: """ Initialize a ProcessingMetrics object. @@ -6858,22 +7324,22 @@ def __init__(self, processed_audio: 'ProcessedAudio', def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} - if 'processed_audio' in _dict: - args['processed_audio'] = ProcessedAudio.from_dict( - _dict.get('processed_audio')) + if (processed_audio := _dict.get('processed_audio')) is not None: + args['processed_audio'] = ProcessedAudio.from_dict(processed_audio) else: raise ValueError( 'Required property \'processed_audio\' not present in ProcessingMetrics JSON' ) - if 'wall_clock_since_first_byte_received' in _dict: - args['wall_clock_since_first_byte_received'] = _dict.get( - 'wall_clock_since_first_byte_received') + if (wall_clock_since_first_byte_received := + _dict.get('wall_clock_since_first_byte_received')) is not None: + args[ + 'wall_clock_since_first_byte_received'] = wall_clock_since_first_byte_received else: raise ValueError( 'Required property \'wall_clock_since_first_byte_received\' not present in ProcessingMetrics JSON' ) - if 'periodic' in _dict: - args['periodic'] = _dict.get('periodic') + if (periodic := _dict.get('periodic')) is not None: + args['periodic'] = periodic else: raise ValueError( 'Required property \'periodic\' not present in ProcessingMetrics JSON' @@ -6921,12 +7387,12 @@ def __ne__(self, other: 'ProcessingMetrics') -> bool: return not self == other -class RecognitionJob(): +class RecognitionJob: """ Information about a current asynchronous speech recognition job. - :attr str id: The ID of the asynchronous job. - :attr str status: The current status of the job: + :param str id: The ID of the asynchronous job. + :param str status: The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns this status when the job is initially created or when it is waiting for capacity to process the job. The job remains in this state until the service has @@ -6937,24 +7403,24 @@ class RecognitionJob(): sent the results with the callback notification. Otherwise, you must retrieve the results by checking the individual job. * `failed`: The job failed. - :attr str created: The date and time in Coordinated Universal Time (UTC) at + :param str created: The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the [Check jobs](#checkjobs) and [Check a job[(#checkjob) methods. - :attr str url: (optional) The URL to use to request information about the job + :param str url: (optional) The URL to use to request information about the job with the [Check a job](#checkjob) method. This field is returned only by the [Create a job](#createjob) method. - :attr str user_token: (optional) The user token associated with a job that was + :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the [Check jobs](#checkjobs) method. - :attr List[SpeechRecognitionResults] results: (optional) If the status is + :param List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the [Check a job](#checkjob) method. - :attr List[str] warnings: (optional) An array of warning messages about invalid + :param List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The @@ -6964,16 +7430,18 @@ class RecognitionJob(): parameter as `lambdaBias`.). """ - def __init__(self, - id: str, - status: str, - created: str, - *, - updated: str = None, - url: str = None, - user_token: str = None, - results: List['SpeechRecognitionResults'] = None, - warnings: List[str] = None) -> None: + def __init__( + self, + id: str, + status: str, + created: str, + *, + updated: Optional[str] = None, + url: Optional[str] = None, + user_token: Optional[str] = None, + results: Optional[List['SpeechRecognitionResults']] = None, + warnings: Optional[List[str]] = None, + ) -> None: """ Initialize a RecognitionJob object. @@ -7030,36 +7498,35 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( 'Required property \'id\' not present in RecognitionJob JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RecognitionJob JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') + if (created := _dict.get('created')) is not None: + args['created'] = created else: raise ValueError( 'Required property \'created\' not present in RecognitionJob JSON' ) - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'user_token' in _dict: - args['user_token'] = _dict.get('user_token') - if 'results' in _dict: + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (url := _dict.get('url')) is not None: + args['url'] = url + if (user_token := _dict.get('user_token')) is not None: + args['user_token'] = user_token + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResults.from_dict(v) - for v in _dict.get('results') + SpeechRecognitionResults.from_dict(v) for v in results ] - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -7126,22 +7593,26 @@ class StatusEnum(str, Enum): results by checking the individual job. * `failed`: The job failed. """ + WAITING = 'waiting' PROCESSING = 'processing' COMPLETED = 'completed' FAILED = 'failed' -class RecognitionJobs(): +class RecognitionJobs: """ Information about current asynchronous speech recognition jobs. - :attr List[RecognitionJob] recognitions: An array of `RecognitionJob` objects + :param List[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ - def __init__(self, recognitions: List['RecognitionJob']) -> None: + def __init__( + self, + recognitions: List['RecognitionJob'], + ) -> None: """ Initialize a RecognitionJobs object. @@ -7155,9 +7626,9 @@ def __init__(self, recognitions: List['RecognitionJob']) -> None: def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} - if 'recognitions' in _dict: + if (recognitions := _dict.get('recognitions')) is not None: args['recognitions'] = [ - RecognitionJob.from_dict(v) for v in _dict.get('recognitions') + RecognitionJob.from_dict(v) for v in recognitions ] else: raise ValueError( @@ -7202,19 +7673,23 @@ def __ne__(self, other: 'RecognitionJobs') -> bool: return not self == other -class RegisterStatus(): +class RegisterStatus: """ Information about a request to register a callback for asynchronous speech recognition. - :attr str status: The current status of the job: + :param str status: The current status of the job: * `created`: The service successfully allowlisted the callback URL as a result of the call. * `already created`: The URL was already allowlisted. - :attr str url: The callback URL that is successfully registered. + :param str url: The callback URL that is successfully registered. """ - def __init__(self, status: str, url: str) -> None: + def __init__( + self, + status: str, + url: str, + ) -> None: """ Initialize a RegisterStatus object. @@ -7231,14 +7706,14 @@ def __init__(self, status: str, url: str) -> None: def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RegisterStatus JSON' ) - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in RegisterStatus JSON') @@ -7283,33 +7758,41 @@ class StatusEnum(str, Enum): the call. * `already created`: The URL was already allowlisted. """ + CREATED = 'created' ALREADY_CREATED = 'already created' -class SpeakerLabelsResult(): +class SpeakerLabelsResult: """ Information about the speakers from speech recognition results. - :attr float from_: The start time of a word from the transcript. The value + :param float from_: The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array. - :attr float to: The end time of a word from the transcript. The value matches + :param float to: The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array. - :attr int speaker: The numeric identifier that the service assigns to a speaker + :param int speaker: The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered. - :attr float confidence: A score that indicates the service's confidence in its + :param float confidence: A score that indicates the service's confidence in its identification of the speaker in the range of 0.0 to 1.0. - :attr bool final: An indication of whether the service might further change word - and speaker-label results. A value of `true` means that the service guarantees - not to send any further updates for the current or any preceding results; - `false` means that the service might send further updates to the results. + :param bool final: An indication of whether the service might further change + word and speaker-label results. A value of `true` means that the service + guarantees not to send any further updates for the current or any preceding + results; `false` means that the service might send further updates to the + results. """ - def __init__(self, from_: float, to: float, speaker: int, confidence: float, - final: bool) -> None: + def __init__( + self, + from_: float, + to: float, + speaker: int, + confidence: float, + final: bool, + ) -> None: """ Initialize a SpeakerLabelsResult object. @@ -7340,32 +7823,32 @@ def __init__(self, from_: float, to: float, speaker: int, confidence: float, def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - if 'from' in _dict: - args['from_'] = _dict.get('from') + if (from_ := _dict.get('from')) is not None: + args['from_'] = from_ else: raise ValueError( 'Required property \'from\' not present in SpeakerLabelsResult JSON' ) - if 'to' in _dict: - args['to'] = _dict.get('to') + if (to := _dict.get('to')) is not None: + args['to'] = to else: raise ValueError( 'Required property \'to\' not present in SpeakerLabelsResult JSON' ) - if 'speaker' in _dict: - args['speaker'] = _dict.get('speaker') + if (speaker := _dict.get('speaker')) is not None: + args['speaker'] = speaker else: raise ValueError( 'Required property \'speaker\' not present in SpeakerLabelsResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in SpeakerLabelsResult JSON' ) - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeakerLabelsResult JSON' @@ -7411,24 +7894,31 @@ def __ne__(self, other: 'SpeakerLabelsResult') -> bool: return not self == other -class SpeechModel(): +class SpeechModel: """ Information about an available language model. - :attr str name: The name of the model for use as an identifier in calls to the + :param str name: The name of the model for use as an identifier in calls to the service (for example, `en-US_BroadbandModel`). - :attr str language: The language identifier of the model (for example, `en-US`). - :attr int rate: The sampling rate (minimum acceptable rate for audio) used by + :param str language: The language identifier of the model (for example, + `en-US`). + :param int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. - :attr str url: The URI for the model. - :attr SupportedFeatures supported_features: Indicates whether select service + :param str url: The URI for the model. + :param SupportedFeatures supported_features: Indicates whether select service features are supported with the model. - :attr str description: A brief description of the model. + :param str description: A brief description of the model. """ - def __init__(self, name: str, language: str, rate: int, url: str, - supported_features: 'SupportedFeatures', - description: str) -> None: + def __init__( + self, + name: str, + language: str, + rate: int, + url: str, + supported_features: 'SupportedFeatures', + description: str, + ) -> None: """ Initialize a SpeechModel object. @@ -7454,36 +7944,36 @@ def __init__(self, name: str, language: str, rate: int, url: str, def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SpeechModel JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in SpeechModel JSON' ) - if 'rate' in _dict: - args['rate'] = _dict.get('rate') + if (rate := _dict.get('rate')) is not None: + args['rate'] = rate else: raise ValueError( 'Required property \'rate\' not present in SpeechModel JSON') - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SpeechModel JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in SpeechModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in SpeechModel JSON' @@ -7536,15 +8026,18 @@ def __ne__(self, other: 'SpeechModel') -> bool: return not self == other -class SpeechModels(): +class SpeechModels: """ Information about the available language models. - :attr List[SpeechModel] models: An array of `SpeechModel` objects that provides + :param List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ - def __init__(self, models: List['SpeechModel']) -> None: + def __init__( + self, + models: List['SpeechModel'], + ) -> None: """ Initialize a SpeechModels object. @@ -7557,10 +8050,8 @@ def __init__(self, models: List['SpeechModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - SpeechModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [SpeechModel.from_dict(v) for v in models] else: raise ValueError( 'Required property \'models\' not present in SpeechModels JSON') @@ -7603,33 +8094,35 @@ def __ne__(self, other: 'SpeechModels') -> bool: return not self == other -class SpeechRecognitionAlternative(): +class SpeechRecognitionAlternative: """ An alternative transcript from speech recognition results. - :attr str transcript: A transcription of the audio. - :attr float confidence: (optional) A score that indicates the service's + :param str transcript: A transcription of the audio. + :param float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. The service returns a confidence score only for the best alternative and only with results marked as final. - :attr List[str] timestamps: (optional) Time alignments for each word from the + :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. - :attr List[str] word_confidence: (optional) A confidence score for each word of + :param List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.86]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ - def __init__(self, - transcript: str, - *, - confidence: float = None, - timestamps: List[str] = None, - word_confidence: List[str] = None) -> None: + def __init__( + self, + transcript: str, + *, + confidence: Optional[float] = None, + timestamps: Optional[List[str]] = None, + word_confidence: Optional[List[str]] = None, + ) -> None: """ Initialize a SpeechRecognitionAlternative object. @@ -7658,18 +8151,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} - if 'transcript' in _dict: - args['transcript'] = _dict.get('transcript') + if (transcript := _dict.get('transcript')) is not None: + args['transcript'] = transcript else: raise ValueError( 'Required property \'transcript\' not present in SpeechRecognitionAlternative JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'timestamps' in _dict: - args['timestamps'] = _dict.get('timestamps') - if 'word_confidence' in _dict: - args['word_confidence'] = _dict.get('word_confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (timestamps := _dict.get('timestamps')) is not None: + args['timestamps'] = timestamps + if (word_confidence := _dict.get('word_confidence')) is not None: + args['word_confidence'] = word_confidence return cls(**args) @classmethod @@ -7710,31 +8203,31 @@ def __ne__(self, other: 'SpeechRecognitionAlternative') -> bool: return not self == other -class SpeechRecognitionResult(): +class SpeechRecognitionResult: """ Component results for a speech recognition request. - :attr bool final: An indication of whether the transcription results are final: + :param bool final: An indication of whether the transcription results are final: * If `true`, the results for this utterance are final. They are guaranteed not to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. **Note:** Because `final` is a reserved word in Java and Swift, the field is renamed `xFinal` in Java and is escaped with back quotes in Swift. - :attr List[SpeechRecognitionAlternative] alternatives: An array of alternative + :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. - :attr dict keywords_result: (optional) A dictionary (or associative array) whose - keys are the strings specified for `keywords` if both that parameter and + :param dict keywords_result: (optional) A dictionary (or associative array) + whose keys are the strings specified for `keywords` if both that parameter and `keywords_threshold` are specified. The value for each key is an array of matches spotted in the audio for that keyword. Each match is described by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. - :attr List[WordAlternativeResults] word_alternatives: (optional) An array of + :param List[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. - :attr str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` + :param str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` parameter is `true`, describes the reason for the split: * `end_of_data` - The end of the input audio stream. * `full_stop` - A full semantic stop, such as for the conclusion of a @@ -7746,13 +8239,15 @@ class SpeechRecognitionResult(): * `silence` - A pause or silence that is at least as long as the pause interval. """ - def __init__(self, - final: bool, - alternatives: List['SpeechRecognitionAlternative'], - *, - keywords_result: dict = None, - word_alternatives: List['WordAlternativeResults'] = None, - end_of_utterance: str = None) -> None: + def __init__( + self, + final: bool, + alternatives: List['SpeechRecognitionAlternative'], + *, + keywords_result: Optional[dict] = None, + word_alternatives: Optional[List['WordAlternativeResults']] = None, + end_of_utterance: Optional[str] = None, + ) -> None: """ Initialize a SpeechRecognitionResult object. @@ -7800,30 +8295,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeechRecognitionResult JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - SpeechRecognitionAlternative.from_dict(v) - for v in _dict.get('alternatives') + SpeechRecognitionAlternative.from_dict(v) for v in alternatives ] else: raise ValueError( 'Required property \'alternatives\' not present in SpeechRecognitionResult JSON' ) - if 'keywords_result' in _dict: - args['keywords_result'] = _dict.get('keywords_result') - if 'word_alternatives' in _dict: + if (keywords_result := _dict.get('keywords_result')) is not None: + args['keywords_result'] = keywords_result + if (word_alternatives := _dict.get('word_alternatives')) is not None: args['word_alternatives'] = [ - WordAlternativeResults.from_dict(v) - for v in _dict.get('word_alternatives') + WordAlternativeResults.from_dict(v) for v in word_alternatives ] - if 'end_of_utterance' in _dict: - args['end_of_utterance'] = _dict.get('end_of_utterance') + if (end_of_utterance := _dict.get('end_of_utterance')) is not None: + args['end_of_utterance'] = end_of_utterance return cls(**args) @classmethod @@ -7892,17 +8385,18 @@ class EndOfUtteranceEnum(str, Enum): use. * `silence` - A pause or silence that is at least as long as the pause interval. """ + END_OF_DATA = 'end_of_data' FULL_STOP = 'full_stop' RESET = 'reset' SILENCE = 'silence' -class SpeechRecognitionResults(): +class SpeechRecognitionResults: """ The complete results for a speech recognition request. - :attr List[SpeechRecognitionResult] results: (optional) An array of + :param List[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further @@ -7913,24 +8407,24 @@ class SpeechRecognitionResults(): incremented to the lowest index in the array that has changed for new results. For more information, see [Understanding speech recognition results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response). - :attr int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index for additional results that it - sends for new audio for the same request. All results with the same index are - delivered at the same time. The same index can include multiple final results - that are delivered with the same response. - :attr List[SpeakerLabelsResult] speaker_labels: (optional) An array of + :param int result_index: (optional) An index that indicates a change point in + the `results` array. The service increments the index for additional results + that it sends for new audio for the same request. All results with the same + index are delivered at the same time. The same index can include multiple final + results that are delivered with the same response. + :param List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include only the `speaker_labels` field. - :attr ProcessingMetrics processing_metrics: (optional) If processing metrics are - requested, information about the service's processing of the input audio. + :param ProcessingMetrics processing_metrics: (optional) If processing metrics + are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, + :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :attr List[str] warnings: (optional) An array of warning messages associated + :param List[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or @@ -7948,14 +8442,16 @@ class SpeechRecognitionResults(): In both cases, the request succeeds despite the warnings. """ - def __init__(self, - *, - results: List['SpeechRecognitionResult'] = None, - result_index: int = None, - speaker_labels: List['SpeakerLabelsResult'] = None, - processing_metrics: 'ProcessingMetrics' = None, - audio_metrics: 'AudioMetrics' = None, - warnings: List[str] = None) -> None: + def __init__( + self, + *, + results: Optional[List['SpeechRecognitionResult']] = None, + result_index: Optional[int] = None, + speaker_labels: Optional[List['SpeakerLabelsResult']] = None, + processing_metrics: Optional['ProcessingMetrics'] = None, + audio_metrics: Optional['AudioMetrics'] = None, + warnings: Optional[List[str]] = None, + ) -> None: """ Initialize a SpeechRecognitionResults object. @@ -8017,26 +8513,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} - if 'results' in _dict: + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResult.from_dict(v) - for v in _dict.get('results') + SpeechRecognitionResult.from_dict(v) for v in results ] - if 'result_index' in _dict: - args['result_index'] = _dict.get('result_index') - if 'speaker_labels' in _dict: + if (result_index := _dict.get('result_index')) is not None: + args['result_index'] = result_index + if (speaker_labels := _dict.get('speaker_labels')) is not None: args['speaker_labels'] = [ - SpeakerLabelsResult.from_dict(v) - for v in _dict.get('speaker_labels') + SpeakerLabelsResult.from_dict(v) for v in speaker_labels ] - if 'processing_metrics' in _dict: + if (processing_metrics := _dict.get('processing_metrics')) is not None: args['processing_metrics'] = ProcessingMetrics.from_dict( - _dict.get('processing_metrics')) - if 'audio_metrics' in _dict: - args['audio_metrics'] = AudioMetrics.from_dict( - _dict.get('audio_metrics')) - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + processing_metrics) + if (audio_metrics := _dict.get('audio_metrics')) is not None: + args['audio_metrics'] = AudioMetrics.from_dict(audio_metrics) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -8100,15 +8593,15 @@ def __ne__(self, other: 'SpeechRecognitionResults') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Indicates whether select service features are supported with the model. - :attr bool custom_language_model: Indicates whether the customization interface + :param bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. - :attr bool custom_acoustic_model: Indicates whether the customization interface + :param bool custom_acoustic_model: Indicates whether the customization interface can be used to create a custom acoustic model based on the language model. - :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can + :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels are supported for use only with the following languages and models: @@ -8119,18 +8612,20 @@ class SupportedFeatures(): (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish transcription only. Speaker labels are not supported for use with any other languages or models. - :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter - can be used with a next-generation language model. The field is returned only - for next-generation models. Previous-generation models do not support the - `low_latency` parameter. + :param bool low_latency: (optional) Indicates whether the `low_latency` + parameter can be used with a next-generation language model. The field is + returned only for next-generation models. Previous-generation models do not + support the `low_latency` parameter. """ - def __init__(self, - custom_language_model: bool, - custom_acoustic_model: bool, - speaker_labels: bool, - *, - low_latency: bool = None) -> None: + def __init__( + self, + custom_language_model: bool, + custom_acoustic_model: bool, + speaker_labels: bool, + *, + low_latency: Optional[bool] = None, + ) -> None: """ Initialize a SupportedFeatures object. @@ -8167,26 +8662,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_language_model' in _dict: - args['custom_language_model'] = _dict.get('custom_language_model') + if (custom_language_model := + _dict.get('custom_language_model')) is not None: + args['custom_language_model'] = custom_language_model else: raise ValueError( 'Required property \'custom_language_model\' not present in SupportedFeatures JSON' ) - if 'custom_acoustic_model' in _dict: - args['custom_acoustic_model'] = _dict.get('custom_acoustic_model') + if (custom_acoustic_model := + _dict.get('custom_acoustic_model')) is not None: + args['custom_acoustic_model'] = custom_acoustic_model else: raise ValueError( 'Required property \'custom_acoustic_model\' not present in SupportedFeatures JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels else: raise ValueError( 'Required property \'speaker_labels\' not present in SupportedFeatures JSON' ) - if 'low_latency' in _dict: - args['low_latency'] = _dict.get('low_latency') + if (low_latency := _dict.get('low_latency')) is not None: + args['low_latency'] = low_latency return cls(**args) @classmethod @@ -8228,18 +8725,22 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class TrainingResponse(): +class TrainingResponse: """ The response from training of a custom language or custom acoustic model. - :attr List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + :param List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For custom language models, invalid resources are grouped and identified by type of resource. The method can return warnings only if the `strict` parameter is set to `false`. """ - def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: + def __init__( + self, + *, + warnings: Optional[List['TrainingWarning']] = None, + ) -> None: """ Initialize a TrainingResponse object. @@ -8255,10 +8756,8 @@ def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} - if 'warnings' in _dict: - args['warnings'] = [ - TrainingWarning.from_dict(v) for v in _dict.get('warnings') - ] + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [TrainingWarning.from_dict(v) for v in warnings] return cls(**args) @classmethod @@ -8298,20 +8797,24 @@ def __ne__(self, other: 'TrainingResponse') -> bool: return not self == other -class TrainingWarning(): +class TrainingWarning: """ A warning from training of a custom language or custom acoustic model. - :attr str code: An identifier for the type of invalid resources listed in the + :param str code: An identifier for the type of invalid resources listed in the `description` field. - :attr str message: A warning message that lists the invalid resources that are + :param str message: A warning message that lists the invalid resources that are excluded from the custom model's training. The message has the following format: `Analysis of the following {resource_type} has not completed successfully: [{resource_names}]. They will be excluded from custom {model_type} model training.`. """ - def __init__(self, code: str, message: str) -> None: + def __init__( + self, + code: str, + message: str, + ) -> None: """ Initialize a TrainingWarning object. @@ -8330,14 +8833,14 @@ def __init__(self, code: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in TrainingWarning JSON' ) - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message else: raise ValueError( 'Required property \'message\' not present in TrainingWarning JSON' @@ -8380,19 +8883,27 @@ class CodeEnum(str, Enum): """ An identifier for the type of invalid resources listed in the `description` field. """ + INVALID_AUDIO_FILES = 'invalid_audio_files' INVALID_CORPUS_FILES = 'invalid_corpus_files' INVALID_GRAMMAR_FILES = 'invalid_grammar_files' INVALID_WORDS = 'invalid_words' -class Word(): +class Word: """ Information about a word from a custom language model. - :attr str word: A word from the custom model's words resource. The spelling of + :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: An array of as many as five pronunciations for the + :param List[str] mapping_only: (optional) (Optional) Parameter for custom words. + You can use the 'mapping_only' key in custom words as a form of post processing. + A boolean value that indicates whether the added word should be used to + fine-tune the mode for selected next-gen models. This field appears in the + response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the value + set by the user, but would not be used. + :param List[str] sounds_like: An array of as many as five pronunciations for the word. * _For a custom model that is based on a previous-generation model_, in addition to sounds-like pronunciations that were added by a user, the array can include a @@ -8400,7 +8911,7 @@ class Word(): is provided when the word is added to the custom model. * _For a custom model that is based on a next-generation model_, the array can include only sounds-like pronunciations that were added by a user. - :attr str display_as: The spelling of the word that the service uses to display + :param str display_as: The spelling of the word that the service uses to display the word in a transcript. * _For a custom model that is based on a previous-generation model_, the field can contain an empty string if no display-as value is provided for a word that @@ -8409,7 +8920,7 @@ class Word(): * _For a custom model that is based on a next-generation model_, the service uses the spelling of the word as the value of the display-as field when the word is added to the model. - :attr int count: _For a custom model that is based on a previous-generation + :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before @@ -8418,7 +8929,7 @@ class Word(): the number of times it is found in corpora and grammars. _For a custom model that is based on a next-generation model_, the `count` field for any word is always `1`. - :attr List[str] source: An array of sources that describes how the word was + :param List[str] source: An array of sources that describes how the word was added to the custom model's words resource. * _For a custom model that is based on previous-generation model,_ the field includes the name of each corpus and grammar from which the service extracted @@ -8429,19 +8940,22 @@ class Word(): shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. - :attr List[WordError] error: (optional) If the service discovered one or more + :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ - def __init__(self, - word: str, - sounds_like: List[str], - display_as: str, - count: int, - source: List[str], - *, - error: List['WordError'] = None) -> None: + def __init__( + self, + word: str, + sounds_like: List[str], + display_as: str, + count: int, + source: List[str], + *, + mapping_only: Optional[List[str]] = None, + error: Optional[List['WordError']] = None, + ) -> None: """ Initialize a Word object. @@ -8485,11 +8999,19 @@ def __init__(self, shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. + :param List[str] mapping_only: (optional) (Optional) Parameter for custom + words. You can use the 'mapping_only' key in custom words as a form of post + processing. A boolean value that indicates whether the added word should be + used to fine-tune the mode for selected next-gen models. This field appears + in the response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the + value set by the user, but would not be used. :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as self.count = count @@ -8500,33 +9022,35 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like else: raise ValueError( 'Required property \'sounds_like\' not present in Word JSON') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as else: raise ValueError( 'Required property \'display_as\' not present in Word JSON') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in Word JSON') - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in Word JSON') - if 'error' in _dict: - args['error'] = [WordError.from_dict(v) for v in _dict.get('error')] + if (error := _dict.get('error')) is not None: + args['error'] = [WordError.from_dict(v) for v in error] return cls(**args) @classmethod @@ -8539,6 +9063,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: @@ -8576,16 +9102,20 @@ def __ne__(self, other: 'Word') -> bool: return not self == other -class WordAlternativeResult(): +class WordAlternativeResult: """ An alternative hypothesis for a word from speech recognition results. - :attr float confidence: A confidence score for the word alternative hypothesis + :param float confidence: A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. - :attr str word: An alternative hypothesis for a word from the input audio. + :param str word: An alternative hypothesis for a word from the input audio. """ - def __init__(self, confidence: float, word: str) -> None: + def __init__( + self, + confidence: float, + word: str, + ) -> None: """ Initialize a WordAlternativeResult object. @@ -8600,14 +9130,14 @@ def __init__(self, confidence: float, word: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in WordAlternativeResult JSON' ) - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in WordAlternativeResult JSON' @@ -8647,20 +9177,24 @@ def __ne__(self, other: 'WordAlternativeResult') -> bool: return not self == other -class WordAlternativeResults(): +class WordAlternativeResults: """ Information about alternative hypotheses for words from speech recognition results. - :attr float start_time: The start time in seconds of the word from the input + :param float start_time: The start time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr float end_time: The end time in seconds of the word from the input audio + :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr List[WordAlternativeResult] alternatives: An array of alternative + :param List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ - def __init__(self, start_time: float, end_time: float, - alternatives: List['WordAlternativeResult']) -> None: + def __init__( + self, + start_time: float, + end_time: float, + alternatives: List['WordAlternativeResult'], + ) -> None: """ Initialize a WordAlternativeResults object. @@ -8679,22 +9213,21 @@ def __init__(self, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in WordAlternativeResults JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in WordAlternativeResults JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - WordAlternativeResult.from_dict(v) - for v in _dict.get('alternatives') + WordAlternativeResult.from_dict(v) for v in alternatives ] else: raise ValueError( @@ -8743,11 +9276,11 @@ def __ne__(self, other: 'WordAlternativeResults') -> bool: return not self == other -class WordError(): +class WordError: """ An error associated with a word from a custom language model. - :attr str element: A key-value pair that describes an error associated with the + :param str element: A key-value pair that describes an error associated with the definition of a word in the words resource. The pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a @@ -8756,7 +9289,10 @@ class WordError(): '{suggested_string}'."`. """ - def __init__(self, element: str) -> None: + def __init__( + self, + element: str, + ) -> None: """ Initialize a WordError object. @@ -8774,8 +9310,8 @@ def __init__(self, element: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} - if 'element' in _dict: - args['element'] = _dict.get('element') + if (element := _dict.get('element')) is not None: + args['element'] = element else: raise ValueError( 'Required property \'element\' not present in WordError JSON') @@ -8812,16 +9348,19 @@ def __ne__(self, other: 'WordError') -> bool: return not self == other -class Words(): +class Words: """ Information about the words from a custom language model. - :attr List[Word] words: An array of `Word` objects that provides information + :param List[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -8835,8 +9374,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index f2cfe225..23fe1b48 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -30,25 +30,17 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). For phonetic translation, the Arabic, Chinese, Dutch, -Australian English, Korean, and Swedish voices support only IPA, not SPR. +Phonetic Representation (SPR). The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service -support custom prompts only for US English custom models and voices. -Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices -remain available to existing users until 31 March 2023, when they will be removed from the -service and the documentation. *No enhanced neural voices or expressive neural voices are -deprecated.*

For more information, see the [1 March 2023 service -update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) -in the release notes for {{site.data.keyword.texttospeechshort}} for -{{site.data.keyword.cloud_notm}}.{: deprecated} +supports custom prompts only for US English custom models and voices. API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -92,7 +84,10 @@ def __init__( # Voices ######################### - def list_voices(self, **kwargs) -> DetailedResponse: + def list_voices( + self, + **kwargs, + ) -> DetailedResponse: """ List voices. @@ -101,13 +96,6 @@ def list_voices(self, **kwargs) -> DetailedResponse: list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. **See also:** [Listing all voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). @@ -117,9 +105,11 @@ def list_voices(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_voices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voices', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -128,16 +118,22 @@ def list_voices(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/voices' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_voice(self, - voice: str, - *, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_voice( + self, + voice: str, + *, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get a voice. @@ -148,13 +144,6 @@ def get_voice(self, voices](#listvoices) method. **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-specific-voice). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -170,9 +159,11 @@ def get_voice(self, if not voice: raise ValueError('voice must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_voice') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice', + ) headers.update(sdk_headers) params = { @@ -188,10 +179,12 @@ def get_voice(self, path_param_values = self.encode_path_vars(voice) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/voices/{voice}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -200,16 +193,18 @@ def get_voice(self, # Synthesis ######################### - def synthesize(self, - text: str, - *, - accept: str = None, - voice: str = None, - customization_id: str = None, - spell_out_mode: str = None, - rate_percentage: int = None, - pitch_percentage: int = None, - **kwargs) -> DetailedResponse: + def synthesize( + self, + text: str, + *, + accept: Optional[str] = None, + voice: Optional[str] = None, + customization_id: Optional[str] = None, + spell_out_mode: Optional[str] = None, + rate_percentage: Optional[int] = None, + pitch_percentage: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Synthesize audio. @@ -221,13 +216,6 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the @@ -361,9 +349,11 @@ def synthesize(self, headers = { 'Accept': accept, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='synthesize') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='synthesize', + ) headers.update(sdk_headers) params = { @@ -386,11 +376,13 @@ def synthesize(self, del kwargs['headers'] url = '/v1/synthesize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -399,13 +391,15 @@ def synthesize(self, # Pronunciation ######################### - def get_pronunciation(self, - text: str, - *, - voice: str = None, - format: str = None, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_pronunciation( + self, + text: str, + *, + voice: Optional[str] = None, + format: Optional[str] = None, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get pronunciation. @@ -413,13 +407,6 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model. - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -434,9 +421,8 @@ def get_pronunciation(self, **See also:** [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str format: (optional) The phoneme format in which to return the - pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. Omit the parameter to obtain the pronunciation - in the default format. + pronunciation. Omit the parameter to obtain the pronunciation in the + default format. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the specified voice. If @@ -453,9 +439,11 @@ def get_pronunciation(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_pronunciation') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_pronunciation', + ) headers.update(sdk_headers) params = { @@ -471,10 +459,12 @@ def get_pronunciation(self, headers['Accept'] = 'application/json' url = '/v1/pronunciation' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -483,12 +473,14 @@ def get_pronunciation(self, # Custom models ######################### - def create_custom_model(self, - name: str, - *, - language: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_custom_model( + self, + name: str, + *, + language: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom model. @@ -498,13 +490,6 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. :param str name: The name of the new custom model. Use a localized name that matches the language of the custom model. Use a name that describes @@ -528,9 +513,11 @@ def create_custom_model(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_custom_model', + ) headers.update(sdk_headers) data = { @@ -548,18 +535,22 @@ def create_custom_model(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_custom_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_custom_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom models. @@ -581,9 +572,11 @@ def list_custom_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_models', + ) headers.update(sdk_headers) params = { @@ -596,21 +589,25 @@ def list_custom_models(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_custom_model(self, - customization_id: str, - *, - name: str = None, - description: str = None, - words: List['Word'] = None, - **kwargs) -> DetailedResponse: + def update_custom_model( + self, + customization_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + **kwargs, + ) -> DetailedResponse: """ Update a custom model. @@ -656,9 +653,11 @@ def update_custom_model(self, if words is not None: words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_custom_model', + ) headers.update(sdk_headers) data = { @@ -679,16 +678,21 @@ def update_custom_model(self, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom model. @@ -711,9 +715,11 @@ def get_custom_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -725,13 +731,20 @@ def get_custom_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom model. @@ -751,9 +764,11 @@ def delete_custom_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -764,9 +779,11 @@ def delete_custom_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -775,8 +792,12 @@ def delete_custom_model(self, customization_id: str, # Custom words ######################### - def add_words(self, customization_id: str, words: List['Word'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['Word'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -825,9 +846,11 @@ def add_words(self, customization_id: str, words: List['Word'], raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) data = { @@ -847,15 +870,21 @@ def add_words(self, customization_id: str, words: List['Word'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -876,9 +905,11 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -891,18 +922,24 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word: str, - translation: str, - *, - part_of_speech: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -937,9 +974,8 @@ def add_word(self, :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -959,9 +995,11 @@ def add_word(self, if translation is None: raise ValueError('translation must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) data = { @@ -981,16 +1019,22 @@ def add_word(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -1014,9 +1058,11 @@ def get_word(self, customization_id: str, word: str, if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1029,13 +1075,21 @@ def get_word(self, customization_id: str, word: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -1058,9 +1112,11 @@ def delete_word(self, customization_id: str, word: str, if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1072,9 +1128,11 @@ def delete_word(self, customization_id: str, word: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1083,8 +1141,11 @@ def delete_word(self, customization_id: str, word: str, # Custom prompts ######################### - def list_custom_prompts(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_custom_prompts( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom prompts. @@ -1111,9 +1172,11 @@ def list_custom_prompts(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_prompts') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_prompts', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1126,14 +1189,23 @@ def list_custom_prompts(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_custom_prompt(self, customization_id: str, prompt_id: str, - metadata: 'PromptMetadata', file: BinaryIO, - **kwargs) -> DetailedResponse: + def add_custom_prompt( + self, + customization_id: str, + prompt_id: str, + metadata: 'PromptMetadata', + file: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Add a custom prompt. @@ -1245,9 +1317,11 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, if file is None: raise ValueError('file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_custom_prompt', + ) headers.update(sdk_headers) form_data = [] @@ -1265,16 +1339,22 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def get_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom prompt. @@ -1300,9 +1380,11 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1315,13 +1397,21 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom prompt. @@ -1350,9 +1440,11 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1364,9 +1456,11 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1375,7 +1469,10 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, # Speaker models ######################### - def list_speaker_models(self, **kwargs) -> DetailedResponse: + def list_speaker_models( + self, + **kwargs, + ) -> DetailedResponse: """ List speaker models. @@ -1393,9 +1490,11 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_speaker_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_speaker_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1404,13 +1503,21 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def create_speaker_model(self, speaker_name: str, audio: BinaryIO, - **kwargs) -> DetailedResponse: + def create_speaker_model( + self, + speaker_name: str, + audio: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Create a speaker model. @@ -1480,9 +1587,11 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, if audio is None: raise ValueError('audio must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_speaker_model', + ) headers.update(sdk_headers) params = { @@ -1498,16 +1607,22 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: + def get_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a speaker model. @@ -1533,9 +1648,11 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1547,13 +1664,20 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_speaker_model(self, speaker_id: str, - **kwargs) -> DetailedResponse: + def delete_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a speaker model. @@ -1581,9 +1705,11 @@ def delete_speaker_model(self, speaker_id: str, if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1594,9 +1720,11 @@ def delete_speaker_model(self, speaker_id: str, path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1605,7 +1733,11 @@ def delete_speaker_model(self, speaker_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -1633,9 +1765,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -1647,10 +1781,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1665,16 +1801,12 @@ class Voice(str, Enum): """ The voice for which information is to be returned. """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -1698,20 +1830,9 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class SynthesizeEnums: @@ -1726,6 +1847,7 @@ class Accept(str, Enum): specifying an audio format, see **Audio formats (accept types)** in the method description. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' @@ -1754,16 +1876,12 @@ class Voice(str, Enum): * [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -1787,20 +1905,9 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class SpellOutMode(str, Enum): """ @@ -1819,6 +1926,7 @@ class SpellOutMode(str, Enum): For more information, see [Specifying how strings are spelled out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). """ + DEFAULT = 'default' SINGLES = 'singles' PAIRS = 'pairs' @@ -1842,16 +1950,12 @@ class Voice(str, Enum): **See also:** [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -1875,27 +1979,16 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class Format(str, Enum): """ - The phoneme format in which to return the pronunciation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. Omit the - parameter to obtain the pronunciation in the default format. + The phoneme format in which to return the pronunciation. Omit the parameter to + obtain the pronunciation in the default format. """ + IBM = 'ibm' IPA = 'ipa' @@ -1911,8 +2004,7 @@ class Language(str, Enum): are to be returned. Omit the parameter to see all custom models that are owned by the requester. """ - AR_MS = 'ar-MS' - CS_CZ = 'cs-CZ' + DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -1924,12 +2016,8 @@ class Language(str, Enum): FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' - KO_KR = 'ko-KR' - NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' - SV_SE = 'sv-SE' - ZH_CN = 'zh-CN' ############################################################################## @@ -1937,49 +2025,51 @@ class Language(str, Enum): ############################################################################## -class CustomModel(): +class CustomModel: """ Information about an existing custom model. - :attr str customization_id: The customization ID (GUID) of the custom model. The - [Create a custom model](#createcustommodel) method returns only this field. It - does not not return the other fields of this object. - :attr str name: (optional) The name of the custom model. - :attr str language: (optional) The language identifier of the custom model (for + :param str customization_id: The customization ID (GUID) of the custom model. + The [Create a custom model](#createcustommodel) method returns only this field. + It does not not return the other fields of this object. + :param str name: (optional) The name of the custom model. + :param str language: (optional) The language identifier of the custom model (for example, `en-US`). - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom model. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str last_modified: (optional) The date and time in Coordinated Universal + :param str last_modified: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was last modified. The `created` and `updated` fields are equal when a model is first added but has yet to be updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str description: (optional) The description of the custom model. - :attr List[Word] words: (optional) An array of `Word` objects that lists the + :param str description: (optional) The description of the custom model. + :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if no words are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. - :attr List[Prompt] prompts: (optional) An array of `Prompt` objects that + :param List[Prompt] prompts: (optional) An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. """ - def __init__(self, - customization_id: str, - *, - name: str = None, - language: str = None, - owner: str = None, - created: str = None, - last_modified: str = None, - description: str = None, - words: List['Word'] = None, - prompts: List['Prompt'] = None) -> None: + def __init__( + self, + customization_id: str, + *, + name: Optional[str] = None, + language: Optional[str] = None, + owner: Optional[str] = None, + created: Optional[str] = None, + last_modified: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + prompts: Optional[List['Prompt']] = None, + ) -> None: """ Initialize a CustomModel object. @@ -2026,30 +2116,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomModel': """Initialize a CustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in CustomModel JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'last_modified' in _dict: - args['last_modified'] = _dict.get('last_modified') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(v) for v in _dict.get('prompts') - ] + if (name := _dict.get('name')) is not None: + args['name'] = name + if (language := _dict.get('language')) is not None: + args['language'] = language + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (created := _dict.get('created')) is not None: + args['created'] = created + if (last_modified := _dict.get('last_modified')) is not None: + args['last_modified'] = last_modified + if (description := _dict.get('description')) is not None: + args['description'] = description + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] return cls(**args) @classmethod @@ -2112,17 +2200,20 @@ def __ne__(self, other: 'CustomModel') -> bool: return not self == other -class CustomModels(): +class CustomModels: """ Information about existing custom models. - :attr List[CustomModel] customizations: An array of `CustomModel` objects that + :param List[CustomModel] customizations: An array of `CustomModel` objects that provides information about each available custom model. The array is empty if the requesting credentials own no custom models (if no language is specified) or own no custom models for the specified language. """ - def __init__(self, customizations: List['CustomModel']) -> None: + def __init__( + self, + customizations: List['CustomModel'], + ) -> None: """ Initialize a CustomModels object. @@ -2137,9 +2228,9 @@ def __init__(self, customizations: List['CustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'CustomModels': """Initialize a CustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - CustomModel.from_dict(v) for v in _dict.get('customizations') + CustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2184,33 +2275,35 @@ def __ne__(self, other: 'CustomModels') -> bool: return not self == other -class Prompt(): +class Prompt: """ Information about a custom prompt. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. - :attr str speaker_id: (optional) The speaker ID (GUID) of the speaker for which + :param str speaker_id: (optional) The speaker ID (GUID) of the speaker for which the prompt was defined. The field is omitted if no speaker ID was specified. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None, - speaker_id: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a Prompt object. @@ -2241,25 +2334,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Prompt': """Initialize a Prompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in Prompt JSON') - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in Prompt JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Prompt JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (error := _dict.get('error')) is not None: + args['error'] = error + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2301,7 +2394,7 @@ def __ne__(self, other: 'Prompt') -> bool: return not self == other -class PromptMetadata(): +class PromptMetadata: """ Information about the prompt that is to be added to a custom model. The following example of a `PromptMetadata` object includes both the required prompt text and an @@ -2309,17 +2402,22 @@ class PromptMetadata(): `{ "prompt_text": "Thank you and good-bye!", "speaker_id": "823068b2-ed4e-11ea-b6e0-7b6456aa95cc" }`. - :attr str prompt_text: The required written text of the spoken prompt. The + :param str prompt_text: The required written text of the spoken prompt. The length of a prompt's text is limited to a few sentences. Speaking one or two sentences of text is the recommended limit. A prompt cannot contain more than 1000 characters of text. Escape any XML control characters (double quotes, single quotes, ampersands, angle brackets, and slashes) that appear in the text of the prompt. - :attr str speaker_id: (optional) The optional speaker ID (GUID) of a previously + :param str speaker_id: (optional) The optional speaker ID (GUID) of a previously defined speaker model that is to be associated with the prompt. """ - def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: + def __init__( + self, + prompt_text: str, + *, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a PromptMetadata object. @@ -2339,14 +2437,14 @@ def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'PromptMetadata': """Initialize a PromptMetadata object from a json dictionary.""" args = {} - if 'prompt_text' in _dict: - args['prompt_text'] = _dict.get('prompt_text') + if (prompt_text := _dict.get('prompt_text')) is not None: + args['prompt_text'] = prompt_text else: raise ValueError( 'Required property \'prompt_text\' not present in PromptMetadata JSON' ) - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2382,16 +2480,19 @@ def __ne__(self, other: 'PromptMetadata') -> bool: return not self == other -class Prompts(): +class Prompts: """ Information about the custom prompts that are defined for a custom model. - :attr List[Prompt] prompts: An array of `Prompt` objects that provides + :param List[Prompt] prompts: An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. """ - def __init__(self, prompts: List['Prompt']) -> None: + def __init__( + self, + prompts: List['Prompt'], + ) -> None: """ Initialize a Prompts object. @@ -2405,10 +2506,8 @@ def __init__(self, prompts: List['Prompt']) -> None: def from_dict(cls, _dict: Dict) -> 'Prompts': """Initialize a Prompts object from a json dictionary.""" args = {} - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(v) for v in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in Prompts JSON') @@ -2451,16 +2550,19 @@ def __ne__(self, other: 'Prompts') -> bool: return not self == other -class Pronunciation(): +class Pronunciation: """ The pronunciation of the specified text. - :attr str pronunciation: The pronunciation of the specified text in the + :param str pronunciation: The pronunciation of the specified text in the requested voice and format. If a custom model is specified, the pronunciation also reflects that custom model. """ - def __init__(self, pronunciation: str) -> None: + def __init__( + self, + pronunciation: str, + ) -> None: """ Initialize a Pronunciation object. @@ -2474,8 +2576,8 @@ def __init__(self, pronunciation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} - if 'pronunciation' in _dict: - args['pronunciation'] = _dict.get('pronunciation') + if (pronunciation := _dict.get('pronunciation')) is not None: + args['pronunciation'] = pronunciation else: raise ValueError( 'Required property \'pronunciation\' not present in Pronunciation JSON' @@ -2513,15 +2615,19 @@ def __ne__(self, other: 'Pronunciation') -> bool: return not self == other -class Speaker(): +class Speaker: """ Information about a speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker. - :attr str name: The user-defined name of the speaker. + :param str speaker_id: The speaker ID (GUID) of the speaker. + :param str name: The user-defined name of the speaker. """ - def __init__(self, speaker_id: str, name: str) -> None: + def __init__( + self, + speaker_id: str, + name: str, + ) -> None: """ Initialize a Speaker object. @@ -2535,13 +2641,13 @@ def __init__(self, speaker_id: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'Speaker': """Initialize a Speaker object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in Speaker JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Speaker JSON') @@ -2580,19 +2686,22 @@ def __ne__(self, other: 'Speaker') -> bool: return not self == other -class SpeakerCustomModel(): +class SpeakerCustomModel: """ A custom models for which the speaker has defined prompts. - :attr str customization_id: The customization ID (GUID) of a custom model for + :param str customization_id: The customization ID (GUID) of a custom model for which the speaker has defined one or more prompts. - :attr List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that + :param List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that provides information about each prompt that the user has defined for the custom model. """ - def __init__(self, customization_id: str, - prompts: List['SpeakerPrompt']) -> None: + def __init__( + self, + customization_id: str, + prompts: List['SpeakerPrompt'], + ) -> None: """ Initialize a SpeakerCustomModel object. @@ -2609,16 +2718,14 @@ def __init__(self, customization_id: str, def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': """Initialize a SpeakerCustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in SpeakerCustomModel JSON' ) - if 'prompts' in _dict: - args['prompts'] = [ - SpeakerPrompt.from_dict(v) for v in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [SpeakerPrompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in SpeakerCustomModel JSON' @@ -2665,17 +2772,20 @@ def __ne__(self, other: 'SpeakerCustomModel') -> bool: return not self == other -class SpeakerCustomModels(): +class SpeakerCustomModels: """ Custom models for which the speaker has defined prompts. - :attr List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` + :param List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` objects. Each object provides information about the prompts that are defined for a specified speaker in the custom models that are owned by a specified service instance. The array is empty if no prompts are defined for the speaker. """ - def __init__(self, customizations: List['SpeakerCustomModel']) -> None: + def __init__( + self, + customizations: List['SpeakerCustomModel'], + ) -> None: """ Initialize a SpeakerCustomModels object. @@ -2691,10 +2801,9 @@ def __init__(self, customizations: List['SpeakerCustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': """Initialize a SpeakerCustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - SpeakerCustomModel.from_dict(v) - for v in _dict.get('customizations') + SpeakerCustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2739,14 +2848,17 @@ def __ne__(self, other: 'SpeakerCustomModels') -> bool: return not self == other -class SpeakerModel(): +class SpeakerModel: """ The speaker ID of the speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker model. + :param str speaker_id: The speaker ID (GUID) of the speaker model. """ - def __init__(self, speaker_id: str) -> None: + def __init__( + self, + speaker_id: str, + ) -> None: """ Initialize a SpeakerModel object. @@ -2758,8 +2870,8 @@ def __init__(self, speaker_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerModel': """Initialize a SpeakerModel object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in SpeakerModel JSON' @@ -2797,30 +2909,32 @@ def __ne__(self, other: 'SpeakerModel') -> bool: return not self == other -class SpeakerPrompt(): +class SpeakerPrompt: """ A prompt that a speaker has defined for a custom model. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a SpeakerPrompt object. @@ -2847,26 +2961,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeakerPrompt': """Initialize a SpeakerPrompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in SpeakerPrompt JSON' ) - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in SpeakerPrompt JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in SpeakerPrompt JSON' ) - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -2906,16 +3020,19 @@ def __ne__(self, other: 'SpeakerPrompt') -> bool: return not self == other -class Speakers(): +class Speakers: """ Information about all speaker models for the service instance. - :attr List[Speaker] speakers: An array of `Speaker` objects that provides + :param List[Speaker] speakers: An array of `Speaker` objects that provides information about the speakers for the service instance. The array is empty if the service instance has no speakers. """ - def __init__(self, speakers: List['Speaker']) -> None: + def __init__( + self, + speakers: List['Speaker'], + ) -> None: """ Initialize a Speakers object. @@ -2929,10 +3046,8 @@ def __init__(self, speakers: List['Speaker']) -> None: def from_dict(cls, _dict: Dict) -> 'Speakers': """Initialize a Speakers object from a json dictionary.""" args = {} - if 'speakers' in _dict: - args['speakers'] = [ - Speaker.from_dict(v) for v in _dict.get('speakers') - ] + if (speakers := _dict.get('speakers')) is not None: + args['speakers'] = [Speaker.from_dict(v) for v in speakers] else: raise ValueError( 'Required property \'speakers\' not present in Speakers JSON') @@ -2975,30 +3090,32 @@ def __ne__(self, other: 'Speakers') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Additional service features that are supported with the voice. - :attr bool custom_pronunciation: If `true`, the voice can be customized; if + :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). - :attr bool voice_transformation: If `true`, the voice can be transformed by - using the SSML <voice-transformation> element; if `false`, the voice - cannot be transformed. The feature was available only for the now-deprecated - standard voices. You cannot use the feature with neural voices. + :param bool voice_transformation: If `true`, the voice can be transformed by + using the SSML `` element; if `false`, the voice cannot be + transformed. **Note:** The SSML `` element is obsolete. + You can no longer use the element with any supported voice. """ - def __init__(self, custom_pronunciation: bool, - voice_transformation: bool) -> None: + def __init__( + self, + custom_pronunciation: bool, + voice_transformation: bool, + ) -> None: """ Initialize a SupportedFeatures object. :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed - by using the SSML <voice-transformation> element; if `false`, the - voice cannot be transformed. The feature was available only for the - now-deprecated standard voices. You cannot use the feature with neural - voices. + by using the SSML `` element; if `false`, the voice + cannot be transformed. **Note:** The SSML `` element + is obsolete. You can no longer use the element with any supported voice. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @@ -3007,14 +3124,16 @@ def __init__(self, custom_pronunciation: bool, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_pronunciation' in _dict: - args['custom_pronunciation'] = _dict.get('custom_pronunciation') + if (custom_pronunciation := + _dict.get('custom_pronunciation')) is not None: + args['custom_pronunciation'] = custom_pronunciation else: raise ValueError( 'Required property \'custom_pronunciation\' not present in SupportedFeatures JSON' ) - if 'voice_transformation' in _dict: - args['voice_transformation'] = _dict.get('voice_transformation') + if (voice_transformation := + _dict.get('voice_transformation')) is not None: + args['voice_transformation'] = voice_transformation else: raise ValueError( 'Required property \'voice_transformation\' not present in SupportedFeatures JSON' @@ -3056,17 +3175,15 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class Translation(): +class Translation: """ Information about the translation for the specified text. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support only - IPA. A sounds-like is one or more words that, when combined, sound like the - word. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + string of a word either as an IPA translation or as an IBM SPR translation. A + sounds-like is one or more words that, when combined, sound like the word. + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of @@ -3074,16 +3191,20 @@ class Translation(): entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, translation: str, *, part_of_speech: str = None) -> None: + def __init__( + self, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Translation object. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -3099,14 +3220,14 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -3150,6 +3271,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -3169,37 +3291,40 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Voice(): +class Voice: """ Information about an available voice. - :attr str url: The URI of the voice. - :attr str gender: The gender of the voice: `male` or `female`. - :attr str name: The name of the voice. Use this as the voice identifier in all + :param str url: The URI of the voice. + :param str gender: The gender of the voice: `male` or `female`. + :param str name: The name of the voice. Use this as the voice identifier in all requests. - :attr str language: The language and region of the voice (for example, `en-US`). - :attr str description: A textual description of the voice. - :attr bool customizable: If `true`, the voice can be customized; if `false`, the - voice cannot be customized. (Same as `custom_pronunciation`; maintained for + :param str language: The language and region of the voice (for example, + `en-US`). + :param str description: A textual description of the voice. + :param bool customizable: If `true`, the voice can be customized; if `false`, + the voice cannot be customized. (Same as `custom_pronunciation`; maintained for backward compatibility.). - :attr SupportedFeatures supported_features: Additional service features that are - supported with the voice. - :attr CustomModel customization: (optional) Returns information about a + :param SupportedFeatures supported_features: Additional service features that + are supported with the voice. + :param CustomModel customization: (optional) Returns information about a specified custom model. This field is returned only by the [Get a voice](#getvoice) method and only when you specify the customization ID of a custom model. """ - def __init__(self, - url: str, - gender: str, - name: str, - language: str, - description: str, - customizable: bool, - supported_features: 'SupportedFeatures', - *, - customization: 'CustomModel' = None) -> None: + def __init__( + self, + url: str, + gender: str, + name: str, + language: str, + description: str, + customizable: bool, + supported_features: 'SupportedFeatures', + *, + customization: Optional['CustomModel'] = None, + ) -> None: """ Initialize a Voice object. @@ -3233,46 +3358,45 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Voice JSON') - if 'gender' in _dict: - args['gender'] = _dict.get('gender') + if (gender := _dict.get('gender')) is not None: + args['gender'] = gender else: raise ValueError( 'Required property \'gender\' not present in Voice JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Voice JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Voice JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in Voice JSON') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') + if (customizable := _dict.get('customizable')) is not None: + args['customizable'] = customizable else: raise ValueError( 'Required property \'customizable\' not present in Voice JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in Voice JSON' ) - if 'customization' in _dict: - args['customization'] = CustomModel.from_dict( - _dict.get('customization')) + if (customization := _dict.get('customization')) is not None: + args['customization'] = CustomModel.from_dict(customization) return cls(**args) @classmethod @@ -3328,14 +3452,17 @@ def __ne__(self, other: 'Voice') -> bool: return not self == other -class Voices(): +class Voices: """ Information about all available voices. - :attr List[Voice] voices: A list of available voices. + :param List[Voice] voices: A list of available voices. """ - def __init__(self, voices: List['Voice']) -> None: + def __init__( + self, + voices: List['Voice'], + ) -> None: """ Initialize a Voices object. @@ -3347,8 +3474,8 @@ def __init__(self, voices: List['Voice']) -> None: def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} - if 'voices' in _dict: - args['voices'] = [Voice.from_dict(v) for v in _dict.get('voices')] + if (voices := _dict.get('voices')) is not None: + args['voices'] = [Voice.from_dict(v) for v in voices] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -3391,19 +3518,18 @@ def __ne__(self, other: 'Voices') -> bool: return not self == other -class Word(): +class Word: """ Information about a word for the custom model. - :attr str word: The word for the custom model. The maximum length of a word is + :param str word: The word for the custom model. The maximum length of a word is 49 characters. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. A sounds-like + string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. The maximum length of a translation is 499 characters. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of @@ -3411,11 +3537,13 @@ class Word(): entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, - word: str, - translation: str, - *, - part_of_speech: str = None) -> None: + def __init__( + self, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Word object. @@ -3423,11 +3551,9 @@ def __init__(self, word is 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing - the phonetic string of a word either as an IPA or IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support - only IPA. A sounds-like translation consists of one or more words that, - when combined, sound like the word. The maximum length of a translation is - 499 characters. + the phonetic string of a word either as an IPA or IBM SPR translation. A + sounds-like translation consists of one or more words that, when combined, + sound like the word. The maximum length of a translation is 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -3444,18 +3570,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Word JSON') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -3501,6 +3627,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -3520,14 +3647,14 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Words(): +class Words: """ For the [Add custom words](#addwords) method, one or more words that are to be added or updated for the custom model and the translation for each specified word. For the [List custom words](#listwords) method, the words and their translations from the custom model. - :attr List[Word] words: The [Add custom words](#addwords) method accepts an + :param List[Word] words: The [Add custom words](#addwords) method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom model and the word's translation. The [List custom words](#listwords) method returns an array of `Word` objects. @@ -3536,7 +3663,10 @@ class Words(): letters. The array is empty if the custom model contains no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -3555,8 +3685,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 2f21dd16..0daae8c2 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '7.0.1' +__version__ = '8.0.0' diff --git a/setup.py b/setup.py index 8c8bc7c3..0fff3301 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '7.0.1' +__version__ = '8.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 86aa0933..5b307c5e 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -71,7 +70,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestMessage(): + +class TestMessage: """ Test Class for message """ @@ -84,11 +84,13 @@ def test_message_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a MessageInput model message_input_model = {} @@ -164,7 +166,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -226,14 +228,14 @@ def test_message_all_params(self): output=output, user_id=user_id, nodes_visited_details=nodes_visited_details, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'nodes_visited_details={}'.format('true' if nodes_visited_details else 'false') in query_string # Validate body params @@ -263,11 +265,13 @@ def test_message_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -275,7 +279,7 @@ def test_message_required_params(self): # Invoke method response = _service.message( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -299,11 +303,13 @@ def test_message_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -313,7 +319,7 @@ def test_message_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message(**req_copy) @@ -326,6 +332,7 @@ def test_message_value_error_with_retries(self): _service.disable_retries() self.test_message_value_error() + # endregion ############################################################################## # End of Service: Message @@ -336,7 +343,8 @@ def test_message_value_error_with_retries(self): ############################################################################## # region -class TestBulkClassify(): + +class TestBulkClassify: """ Test Class for bulk_classify """ @@ -349,11 +357,13 @@ def test_bulk_classify_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -367,7 +377,7 @@ def test_bulk_classify_all_params(self): response = _service.bulk_classify( workspace_id, input=input, - headers={} + headers={}, ) # Check for correct operation @@ -394,11 +404,13 @@ def test_bulk_classify_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -406,7 +418,7 @@ def test_bulk_classify_required_params(self): # Invoke method response = _service.bulk_classify( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -430,11 +442,13 @@ def test_bulk_classify_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -444,7 +458,7 @@ def test_bulk_classify_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) @@ -457,6 +471,7 @@ def test_bulk_classify_value_error_with_retries(self): _service.disable_retries() self.test_bulk_classify_value_error() + # endregion ############################################################################## # End of Service: BulkClassify @@ -467,7 +482,8 @@ def test_bulk_classify_value_error_with_retries(self): ############################################################################## # region -class TestListWorkspaces(): + +class TestListWorkspaces: """ Test Class for list_workspaces """ @@ -480,14 +496,16 @@ def test_list_workspaces_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -500,14 +518,14 @@ def test_list_workspaces_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -532,16 +550,17 @@ def test_list_workspaces_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_workspaces() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -563,17 +582,19 @@ def test_list_workspaces_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_workspaces(**req_copy) @@ -586,7 +607,8 @@ def test_list_workspaces_value_error_with_retries(self): _service.disable_retries() self.test_list_workspaces_value_error() -class TestCreateWorkspace(): + +class TestCreateWorkspace: """ Test Class for create_workspace """ @@ -599,11 +621,13 @@ def test_create_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -618,7 +642,7 @@ def test_create_workspace_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -628,13 +652,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -647,7 +671,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -660,7 +684,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -707,7 +731,7 @@ def test_create_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -745,7 +769,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -754,7 +778,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -764,7 +788,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -786,14 +810,14 @@ def test_create_workspace_all_params(self): intents=intents, entities=entities, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -803,7 +827,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -827,16 +851,17 @@ def test_create_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Invoke method response = _service.create_workspace() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 @@ -858,17 +883,19 @@ def test_create_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_workspace(**req_copy) @@ -881,7 +908,8 @@ def test_create_workspace_value_error_with_retries(self): _service.disable_retries() self.test_create_workspace_value_error() -class TestGetWorkspace(): + +class TestGetWorkspace: """ Test Class for get_workspace """ @@ -894,11 +922,13 @@ def test_get_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -912,14 +942,14 @@ def test_get_workspace_all_params(self): export=export, include_audit=include_audit, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -942,11 +972,13 @@ def test_get_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -954,7 +986,7 @@ def test_get_workspace_required_params(self): # Invoke method response = _service.get_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -978,11 +1010,13 @@ def test_get_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -992,7 +1026,7 @@ def test_get_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_workspace(**req_copy) @@ -1005,7 +1039,8 @@ def test_get_workspace_value_error_with_retries(self): _service.disable_retries() self.test_get_workspace_value_error() -class TestUpdateWorkspace(): + +class TestUpdateWorkspace: """ Test Class for update_workspace """ @@ -1018,11 +1053,13 @@ def test_update_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1037,7 +1074,7 @@ def test_update_workspace_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1047,13 +1084,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1066,7 +1103,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1079,7 +1116,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1126,7 +1163,7 @@ def test_update_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1164,7 +1201,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1173,7 +1210,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1184,7 +1221,7 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1209,14 +1246,14 @@ def test_update_workspace_all_params(self): entities=entities, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1227,7 +1264,7 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1251,11 +1288,13 @@ def test_update_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1263,7 +1302,7 @@ def test_update_workspace_required_params(self): # Invoke method response = _service.update_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1287,11 +1326,13 @@ def test_update_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1301,7 +1342,7 @@ def test_update_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_workspace(**req_copy) @@ -1314,7 +1355,8 @@ def test_update_workspace_value_error_with_retries(self): _service.disable_retries() self.test_update_workspace_value_error() -class TestDeleteWorkspace(): + +class TestDeleteWorkspace: """ Test Class for delete_workspace """ @@ -1326,9 +1368,11 @@ def test_delete_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1336,7 +1380,7 @@ def test_delete_workspace_all_params(self): # Invoke method response = _service.delete_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1359,9 +1403,11 @@ def test_delete_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1371,7 +1417,7 @@ def test_delete_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_workspace(**req_copy) @@ -1384,7 +1430,8 @@ def test_delete_workspace_value_error_with_retries(self): _service.disable_retries() self.test_delete_workspace_value_error() -class TestCreateWorkspaceAsync(): + +class TestCreateWorkspaceAsync: """ Test Class for create_workspace_async """ @@ -1397,11 +1444,13 @@ def test_create_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1416,7 +1465,7 @@ def test_create_workspace_async_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1426,13 +1475,13 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1445,7 +1494,7 @@ def test_create_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1458,7 +1507,7 @@ def test_create_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1505,7 +1554,7 @@ def test_create_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1543,7 +1592,7 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1552,7 +1601,7 @@ def test_create_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1562,7 +1611,7 @@ def test_create_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1582,7 +1631,7 @@ def test_create_workspace_async_all_params(self): webhooks=webhooks, intents=intents, entities=entities, - headers={} + headers={}, ) # Check for correct operation @@ -1595,7 +1644,7 @@ def test_create_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1619,16 +1668,17 @@ def test_create_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Invoke method response = _service.create_workspace_async() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 @@ -1650,17 +1700,19 @@ def test_create_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_workspace_async(**req_copy) @@ -1673,7 +1725,8 @@ def test_create_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_create_workspace_async_value_error() -class TestUpdateWorkspaceAsync(): + +class TestUpdateWorkspaceAsync: """ Test Class for update_workspace_async """ @@ -1686,11 +1739,13 @@ def test_update_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1705,7 +1760,7 @@ def test_update_workspace_async_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1715,13 +1770,13 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1734,7 +1789,7 @@ def test_update_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1747,7 +1802,7 @@ def test_update_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1794,7 +1849,7 @@ def test_update_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1832,7 +1887,7 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1841,7 +1896,7 @@ def test_update_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1852,7 +1907,7 @@ def test_update_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1875,14 +1930,14 @@ def test_update_workspace_async_all_params(self): intents=intents, entities=entities, append=append, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string # Validate body params @@ -1892,7 +1947,7 @@ def test_update_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1916,11 +1971,13 @@ def test_update_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values workspace_id = 'testString' @@ -1928,7 +1985,7 @@ def test_update_workspace_async_required_params(self): # Invoke method response = _service.update_workspace_async( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1952,11 +2009,13 @@ def test_update_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values workspace_id = 'testString' @@ -1966,7 +2025,7 @@ def test_update_workspace_async_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_workspace_async(**req_copy) @@ -1979,7 +2038,8 @@ def test_update_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_update_workspace_async_value_error() -class TestExportWorkspaceAsync(): + +class TestExportWorkspaceAsync: """ Test Class for export_workspace_async """ @@ -1992,11 +2052,13 @@ def test_export_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2010,14 +2072,14 @@ def test_export_workspace_async_all_params(self): include_audit=include_audit, sort=sort, verbose=verbose, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string assert 'sort={}'.format(sort) in query_string @@ -2040,11 +2102,13 @@ def test_export_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2052,7 +2116,7 @@ def test_export_workspace_async_required_params(self): # Invoke method response = _service.export_workspace_async( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -2076,11 +2140,13 @@ def test_export_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2090,7 +2156,7 @@ def test_export_workspace_async_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.export_workspace_async(**req_copy) @@ -2103,6 +2169,7 @@ def test_export_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_export_workspace_async_value_error() + # endregion ############################################################################## # End of Service: Workspaces @@ -2113,7 +2180,8 @@ def test_export_workspace_async_value_error_with_retries(self): ############################################################################## # region -class TestListIntents(): + +class TestListIntents: """ Test Class for list_intents """ @@ -2126,16 +2194,18 @@ def test_list_intents_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'intent' cursor = 'testString' @@ -2150,14 +2220,14 @@ def test_list_intents_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -2183,11 +2253,13 @@ def test_list_intents_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2195,7 +2267,7 @@ def test_list_intents_required_params(self): # Invoke method response = _service.list_intents( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -2219,11 +2291,13 @@ def test_list_intents_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2233,7 +2307,7 @@ def test_list_intents_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_intents(**req_copy) @@ -2246,7 +2320,8 @@ def test_list_intents_value_error_with_retries(self): _service.disable_retries() self.test_list_intents_value_error() -class TestCreateIntent(): + +class TestCreateIntent: """ Test Class for create_intent """ @@ -2259,11 +2334,13 @@ def test_create_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2289,14 +2366,14 @@ def test_create_intent_all_params(self): description=description, examples=examples, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2322,11 +2399,13 @@ def test_create_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2350,7 +2429,7 @@ def test_create_intent_required_params(self): intent, description=description, examples=examples, - headers={} + headers={}, ) # Check for correct operation @@ -2379,11 +2458,13 @@ def test_create_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2407,7 +2488,7 @@ def test_create_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_intent(**req_copy) @@ -2420,7 +2501,8 @@ def test_create_intent_value_error_with_retries(self): _service.disable_retries() self.test_create_intent_value_error() -class TestGetIntent(): + +class TestGetIntent: """ Test Class for get_intent """ @@ -2433,11 +2515,13 @@ def test_get_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2451,14 +2535,14 @@ def test_get_intent_all_params(self): intent, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2480,11 +2564,13 @@ def test_get_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2494,7 +2580,7 @@ def test_get_intent_required_params(self): response = _service.get_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2518,11 +2604,13 @@ def test_get_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2534,7 +2622,7 @@ def test_get_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_intent(**req_copy) @@ -2547,7 +2635,8 @@ def test_get_intent_value_error_with_retries(self): _service.disable_retries() self.test_get_intent_value_error() -class TestUpdateIntent(): + +class TestUpdateIntent: """ Test Class for update_intent """ @@ -2560,11 +2649,13 @@ def test_update_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2594,14 +2685,14 @@ def test_update_intent_all_params(self): new_examples=new_examples, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2628,11 +2719,13 @@ def test_update_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2658,7 +2751,7 @@ def test_update_intent_required_params(self): new_intent=new_intent, new_description=new_description, new_examples=new_examples, - headers={} + headers={}, ) # Check for correct operation @@ -2687,11 +2780,13 @@ def test_update_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2716,7 +2811,7 @@ def test_update_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_intent(**req_copy) @@ -2729,7 +2824,8 @@ def test_update_intent_value_error_with_retries(self): _service.disable_retries() self.test_update_intent_value_error() -class TestDeleteIntent(): + +class TestDeleteIntent: """ Test Class for delete_intent """ @@ -2741,9 +2837,11 @@ def test_delete_intent_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2753,7 +2851,7 @@ def test_delete_intent_all_params(self): response = _service.delete_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2776,9 +2874,11 @@ def test_delete_intent_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2790,7 +2890,7 @@ def test_delete_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_intent(**req_copy) @@ -2803,6 +2903,7 @@ def test_delete_intent_value_error_with_retries(self): _service.disable_retries() self.test_delete_intent_value_error() + # endregion ############################################################################## # End of Service: Intents @@ -2813,7 +2914,8 @@ def test_delete_intent_value_error_with_retries(self): ############################################################################## # region -class TestListExamples(): + +class TestListExamples: """ Test Class for list_examples """ @@ -2826,16 +2928,18 @@ def test_list_examples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' intent = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -2850,14 +2954,14 @@ def test_list_examples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2882,11 +2986,13 @@ def test_list_examples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2896,7 +3002,7 @@ def test_list_examples_required_params(self): response = _service.list_examples( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2920,11 +3026,13 @@ def test_list_examples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2936,7 +3044,7 @@ def test_list_examples_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_examples(**req_copy) @@ -2949,7 +3057,8 @@ def test_list_examples_value_error_with_retries(self): _service.disable_retries() self.test_list_examples_value_error() -class TestCreateExample(): + +class TestCreateExample: """ Test Class for create_example """ @@ -2962,11 +3071,13 @@ def test_create_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2987,14 +3098,14 @@ def test_create_example_all_params(self): text, mentions=mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3019,11 +3130,13 @@ def test_create_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3042,7 +3155,7 @@ def test_create_example_required_params(self): intent, text, mentions=mentions, - headers={} + headers={}, ) # Check for correct operation @@ -3070,11 +3183,13 @@ def test_create_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3094,7 +3209,7 @@ def test_create_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_example(**req_copy) @@ -3107,7 +3222,8 @@ def test_create_example_value_error_with_retries(self): _service.disable_retries() self.test_create_example_value_error() -class TestGetExample(): + +class TestGetExample: """ Test Class for get_example """ @@ -3120,11 +3236,13 @@ def test_get_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3138,14 +3256,14 @@ def test_get_example_all_params(self): intent, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3166,11 +3284,13 @@ def test_get_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3182,7 +3302,7 @@ def test_get_example_required_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -3206,11 +3326,13 @@ def test_get_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3224,7 +3346,7 @@ def test_get_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_example(**req_copy) @@ -3237,7 +3359,8 @@ def test_get_example_value_error_with_retries(self): _service.disable_retries() self.test_get_example_value_error() -class TestUpdateExample(): + +class TestUpdateExample: """ Test Class for update_example """ @@ -3250,11 +3373,13 @@ def test_update_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3277,14 +3402,14 @@ def test_update_example_all_params(self): new_text=new_text, new_mentions=new_mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3309,11 +3434,13 @@ def test_update_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3334,7 +3461,7 @@ def test_update_example_required_params(self): text, new_text=new_text, new_mentions=new_mentions, - headers={} + headers={}, ) # Check for correct operation @@ -3362,11 +3489,13 @@ def test_update_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3387,7 +3516,7 @@ def test_update_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_example(**req_copy) @@ -3400,7 +3529,8 @@ def test_update_example_value_error_with_retries(self): _service.disable_retries() self.test_update_example_value_error() -class TestDeleteExample(): + +class TestDeleteExample: """ Test Class for delete_example """ @@ -3412,9 +3542,11 @@ def test_delete_example_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3426,7 +3558,7 @@ def test_delete_example_all_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -3449,9 +3581,11 @@ def test_delete_example_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3465,7 +3599,7 @@ def test_delete_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_example(**req_copy) @@ -3478,6 +3612,7 @@ def test_delete_example_value_error_with_retries(self): _service.disable_retries() self.test_delete_example_value_error() + # endregion ############################################################################## # End of Service: Examples @@ -3488,7 +3623,8 @@ def test_delete_example_value_error_with_retries(self): ############################################################################## # region -class TestListCounterexamples(): + +class TestListCounterexamples: """ Test Class for list_counterexamples """ @@ -3501,15 +3637,17 @@ def test_list_counterexamples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -3523,14 +3661,14 @@ def test_list_counterexamples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -3555,11 +3693,13 @@ def test_list_counterexamples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3567,7 +3707,7 @@ def test_list_counterexamples_required_params(self): # Invoke method response = _service.list_counterexamples( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -3591,11 +3731,13 @@ def test_list_counterexamples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3605,7 +3747,7 @@ def test_list_counterexamples_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_counterexamples(**req_copy) @@ -3618,7 +3760,8 @@ def test_list_counterexamples_value_error_with_retries(self): _service.disable_retries() self.test_list_counterexamples_value_error() -class TestCreateCounterexample(): + +class TestCreateCounterexample: """ Test Class for create_counterexample """ @@ -3631,11 +3774,13 @@ def test_create_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3647,14 +3792,14 @@ def test_create_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3678,11 +3823,13 @@ def test_create_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3692,7 +3839,7 @@ def test_create_counterexample_required_params(self): response = _service.create_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3719,11 +3866,13 @@ def test_create_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3735,7 +3884,7 @@ def test_create_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_counterexample(**req_copy) @@ -3748,7 +3897,8 @@ def test_create_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_create_counterexample_value_error() -class TestGetCounterexample(): + +class TestGetCounterexample: """ Test Class for get_counterexample """ @@ -3761,11 +3911,13 @@ def test_get_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3777,14 +3929,14 @@ def test_get_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3805,11 +3957,13 @@ def test_get_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3819,7 +3973,7 @@ def test_get_counterexample_required_params(self): response = _service.get_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3843,11 +3997,13 @@ def test_get_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3859,7 +4015,7 @@ def test_get_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_counterexample(**req_copy) @@ -3872,7 +4028,8 @@ def test_get_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_get_counterexample_value_error() -class TestUpdateCounterexample(): + +class TestUpdateCounterexample: """ Test Class for update_counterexample """ @@ -3885,11 +4042,13 @@ def test_update_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3903,14 +4062,14 @@ def test_update_counterexample_all_params(self): text, new_text=new_text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3934,11 +4093,13 @@ def test_update_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3950,7 +4111,7 @@ def test_update_counterexample_required_params(self): workspace_id, text, new_text=new_text, - headers={} + headers={}, ) # Check for correct operation @@ -3977,11 +4138,13 @@ def test_update_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3994,7 +4157,7 @@ def test_update_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_counterexample(**req_copy) @@ -4007,7 +4170,8 @@ def test_update_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_update_counterexample_value_error() -class TestDeleteCounterexample(): + +class TestDeleteCounterexample: """ Test Class for delete_counterexample """ @@ -4019,9 +4183,11 @@ def test_delete_counterexample_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4031,7 +4197,7 @@ def test_delete_counterexample_all_params(self): response = _service.delete_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -4054,9 +4220,11 @@ def test_delete_counterexample_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4068,7 +4236,7 @@ def test_delete_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_counterexample(**req_copy) @@ -4081,6 +4249,7 @@ def test_delete_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_delete_counterexample_value_error() + # endregion ############################################################################## # End of Service: Counterexamples @@ -4091,7 +4260,8 @@ def test_delete_counterexample_value_error_with_retries(self): ############################################################################## # region -class TestListEntities(): + +class TestListEntities: """ Test Class for list_entities """ @@ -4104,16 +4274,18 @@ def test_list_entities_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'entity' cursor = 'testString' @@ -4128,14 +4300,14 @@ def test_list_entities_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -4161,11 +4333,13 @@ def test_list_entities_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4173,7 +4347,7 @@ def test_list_entities_required_params(self): # Invoke method response = _service.list_entities( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -4197,11 +4371,13 @@ def test_list_entities_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4211,7 +4387,7 @@ def test_list_entities_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_entities(**req_copy) @@ -4224,7 +4400,8 @@ def test_list_entities_value_error_with_retries(self): _service.disable_retries() self.test_list_entities_value_error() -class TestCreateEntity(): + +class TestCreateEntity: """ Test Class for create_entity """ @@ -4237,16 +4414,18 @@ def test_create_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4255,7 +4434,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -4269,21 +4448,21 @@ def test_create_entity_all_params(self): fuzzy_match=fuzzy_match, values=values, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4304,16 +4483,18 @@ def test_create_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4322,7 +4503,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -4334,7 +4515,7 @@ def test_create_entity_required_params(self): metadata=metadata, fuzzy_match=fuzzy_match, values=values, - headers={} + headers={}, ) # Check for correct operation @@ -4344,7 +4525,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4365,16 +4546,18 @@ def test_create_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4383,7 +4566,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -4393,7 +4576,7 @@ def test_create_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_entity(**req_copy) @@ -4406,7 +4589,8 @@ def test_create_entity_value_error_with_retries(self): _service.disable_retries() self.test_create_entity_value_error() -class TestGetEntity(): + +class TestGetEntity: """ Test Class for get_entity """ @@ -4419,11 +4603,13 @@ def test_get_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4437,14 +4623,14 @@ def test_get_entity_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4466,11 +4652,13 @@ def test_get_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4480,7 +4668,7 @@ def test_get_entity_required_params(self): response = _service.get_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4504,11 +4692,13 @@ def test_get_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4520,7 +4710,7 @@ def test_get_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_entity(**req_copy) @@ -4533,7 +4723,8 @@ def test_get_entity_value_error_with_retries(self): _service.disable_retries() self.test_get_entity_value_error() -class TestUpdateEntity(): + +class TestUpdateEntity: """ Test Class for update_entity """ @@ -4546,16 +4737,18 @@ def test_update_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4565,7 +4758,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -4582,14 +4775,14 @@ def test_update_entity_all_params(self): new_values=new_values, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4597,7 +4790,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4618,16 +4811,18 @@ def test_update_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4637,7 +4832,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -4650,7 +4845,7 @@ def test_update_entity_required_params(self): new_metadata=new_metadata, new_fuzzy_match=new_fuzzy_match, new_values=new_values, - headers={} + headers={}, ) # Check for correct operation @@ -4660,7 +4855,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4681,16 +4876,18 @@ def test_update_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4700,7 +4897,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -4710,7 +4907,7 @@ def test_update_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_entity(**req_copy) @@ -4723,7 +4920,8 @@ def test_update_entity_value_error_with_retries(self): _service.disable_retries() self.test_update_entity_value_error() -class TestDeleteEntity(): + +class TestDeleteEntity: """ Test Class for delete_entity """ @@ -4735,9 +4933,11 @@ def test_delete_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4747,7 +4947,7 @@ def test_delete_entity_all_params(self): response = _service.delete_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4770,9 +4970,11 @@ def test_delete_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4784,7 +4986,7 @@ def test_delete_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_entity(**req_copy) @@ -4797,6 +4999,7 @@ def test_delete_entity_value_error_with_retries(self): _service.disable_retries() self.test_delete_entity_value_error() + # endregion ############################################################################## # End of Service: Entities @@ -4807,7 +5010,8 @@ def test_delete_entity_value_error_with_retries(self): ############################################################################## # region -class TestListMentions(): + +class TestListMentions: """ Test Class for list_mentions """ @@ -4820,11 +5024,13 @@ def test_list_mentions_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4838,14 +5044,14 @@ def test_list_mentions_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4867,11 +5073,13 @@ def test_list_mentions_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4881,7 +5089,7 @@ def test_list_mentions_required_params(self): response = _service.list_mentions( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4905,11 +5113,13 @@ def test_list_mentions_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4921,7 +5131,7 @@ def test_list_mentions_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_mentions(**req_copy) @@ -4934,6 +5144,7 @@ def test_list_mentions_value_error_with_retries(self): _service.disable_retries() self.test_list_mentions_value_error() + # endregion ############################################################################## # End of Service: Mentions @@ -4944,7 +5155,8 @@ def test_list_mentions_value_error_with_retries(self): ############################################################################## # region -class TestListValues(): + +class TestListValues: """ Test Class for list_values """ @@ -4957,17 +5169,19 @@ def test_list_values_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'value' cursor = 'testString' @@ -4983,14 +5197,14 @@ def test_list_values_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -5016,11 +5230,13 @@ def test_list_values_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5030,7 +5246,7 @@ def test_list_values_required_params(self): response = _service.list_values( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -5054,11 +5270,13 @@ def test_list_values_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5070,7 +5288,7 @@ def test_list_values_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_values(**req_copy) @@ -5083,7 +5301,8 @@ def test_list_values_value_error_with_retries(self): _service.disable_retries() self.test_list_values_value_error() -class TestCreateValue(): + +class TestCreateValue: """ Test Class for create_value """ @@ -5096,17 +5315,19 @@ def test_create_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5122,20 +5343,20 @@ def test_create_value_all_params(self): synonyms=synonyms, patterns=patterns, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5157,17 +5378,19 @@ def test_create_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5181,7 +5404,7 @@ def test_create_value_required_params(self): type=type, synonyms=synonyms, patterns=patterns, - headers={} + headers={}, ) # Check for correct operation @@ -5190,7 +5413,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5212,17 +5435,19 @@ def test_create_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5234,7 +5459,7 @@ def test_create_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_value(**req_copy) @@ -5247,7 +5472,8 @@ def test_create_value_value_error_with_retries(self): _service.disable_retries() self.test_create_value_value_error() -class TestGetValue(): + +class TestGetValue: """ Test Class for get_value """ @@ -5260,11 +5486,13 @@ def test_get_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5280,14 +5508,14 @@ def test_get_value_all_params(self): value, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -5309,11 +5537,13 @@ def test_get_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5325,7 +5555,7 @@ def test_get_value_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5349,11 +5579,13 @@ def test_get_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5367,7 +5599,7 @@ def test_get_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_value(**req_copy) @@ -5380,7 +5612,8 @@ def test_get_value_value_error_with_retries(self): _service.disable_retries() self.test_get_value_value_error() -class TestUpdateValue(): + +class TestUpdateValue: """ Test Class for update_value """ @@ -5393,18 +5626,20 @@ def test_update_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5423,21 +5658,21 @@ def test_update_value_all_params(self): new_patterns=new_patterns, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5459,18 +5694,20 @@ def test_update_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5485,7 +5722,7 @@ def test_update_value_required_params(self): new_type=new_type, new_synonyms=new_synonyms, new_patterns=new_patterns, - headers={} + headers={}, ) # Check for correct operation @@ -5494,7 +5731,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5516,18 +5753,20 @@ def test_update_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5539,7 +5778,7 @@ def test_update_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_value(**req_copy) @@ -5552,7 +5791,8 @@ def test_update_value_value_error_with_retries(self): _service.disable_retries() self.test_update_value_value_error() -class TestDeleteValue(): + +class TestDeleteValue: """ Test Class for delete_value """ @@ -5564,9 +5804,11 @@ def test_delete_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5578,7 +5820,7 @@ def test_delete_value_all_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5601,9 +5843,11 @@ def test_delete_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5617,7 +5861,7 @@ def test_delete_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_value(**req_copy) @@ -5630,6 +5874,7 @@ def test_delete_value_value_error_with_retries(self): _service.disable_retries() self.test_delete_value_value_error() + # endregion ############################################################################## # End of Service: Values @@ -5640,7 +5885,8 @@ def test_delete_value_value_error_with_retries(self): ############################################################################## # region -class TestListSynonyms(): + +class TestListSynonyms: """ Test Class for list_synonyms """ @@ -5653,17 +5899,19 @@ def test_list_synonyms_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'synonym' cursor = 'testString' @@ -5679,14 +5927,14 @@ def test_list_synonyms_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -5711,11 +5959,13 @@ def test_list_synonyms_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5727,7 +5977,7 @@ def test_list_synonyms_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5751,11 +6001,13 @@ def test_list_synonyms_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5769,7 +6021,7 @@ def test_list_synonyms_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_synonyms(**req_copy) @@ -5782,7 +6034,8 @@ def test_list_synonyms_value_error_with_retries(self): _service.disable_retries() self.test_list_synonyms_value_error() -class TestCreateSynonym(): + +class TestCreateSynonym: """ Test Class for create_synonym """ @@ -5795,11 +6048,13 @@ def test_create_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5815,14 +6070,14 @@ def test_create_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -5846,11 +6101,13 @@ def test_create_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5864,7 +6121,7 @@ def test_create_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5891,11 +6148,13 @@ def test_create_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5911,7 +6170,7 @@ def test_create_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_synonym(**req_copy) @@ -5924,7 +6183,8 @@ def test_create_synonym_value_error_with_retries(self): _service.disable_retries() self.test_create_synonym_value_error() -class TestGetSynonym(): + +class TestGetSynonym: """ Test Class for get_synonym """ @@ -5937,11 +6197,13 @@ def test_get_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5957,14 +6219,14 @@ def test_get_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -5985,11 +6247,13 @@ def test_get_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6003,7 +6267,7 @@ def test_get_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6027,11 +6291,13 @@ def test_get_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6047,7 +6313,7 @@ def test_get_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_synonym(**req_copy) @@ -6060,7 +6326,8 @@ def test_get_synonym_value_error_with_retries(self): _service.disable_retries() self.test_get_synonym_value_error() -class TestUpdateSynonym(): + +class TestUpdateSynonym: """ Test Class for update_synonym """ @@ -6073,11 +6340,13 @@ def test_update_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6095,14 +6364,14 @@ def test_update_synonym_all_params(self): synonym, new_synonym=new_synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -6126,11 +6395,13 @@ def test_update_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6146,7 +6417,7 @@ def test_update_synonym_required_params(self): value, synonym, new_synonym=new_synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6173,11 +6444,13 @@ def test_update_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6194,7 +6467,7 @@ def test_update_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_synonym(**req_copy) @@ -6207,7 +6480,8 @@ def test_update_synonym_value_error_with_retries(self): _service.disable_retries() self.test_update_synonym_value_error() -class TestDeleteSynonym(): + +class TestDeleteSynonym: """ Test Class for delete_synonym """ @@ -6219,9 +6493,11 @@ def test_delete_synonym_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6235,7 +6511,7 @@ def test_delete_synonym_all_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6258,9 +6534,11 @@ def test_delete_synonym_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6276,7 +6554,7 @@ def test_delete_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_synonym(**req_copy) @@ -6289,6 +6567,7 @@ def test_delete_synonym_value_error_with_retries(self): _service.disable_retries() self.test_delete_synonym_value_error() + # endregion ############################################################################## # End of Service: Synonyms @@ -6299,7 +6578,8 @@ def test_delete_synonym_value_error_with_retries(self): ############################################################################## # region -class TestListDialogNodes(): + +class TestListDialogNodes: """ Test Class for list_dialog_nodes """ @@ -6312,15 +6592,17 @@ def test_list_dialog_nodes_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'dialog_node' cursor = 'testString' @@ -6334,14 +6616,14 @@ def test_list_dialog_nodes_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -6366,11 +6648,13 @@ def test_list_dialog_nodes_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6378,7 +6662,7 @@ def test_list_dialog_nodes_required_params(self): # Invoke method response = _service.list_dialog_nodes( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -6402,11 +6686,13 @@ def test_list_dialog_nodes_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6416,7 +6702,7 @@ def test_list_dialog_nodes_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_dialog_nodes(**req_copy) @@ -6429,7 +6715,8 @@ def test_list_dialog_nodes_value_error_with_retries(self): _service.disable_retries() self.test_list_dialog_nodes_value_error() -class TestCreateDialogNode(): + +class TestCreateDialogNode: """ Test Class for create_dialog_node """ @@ -6442,11 +6729,13 @@ def test_create_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6461,7 +6750,7 @@ def test_create_dialog_node_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6471,13 +6760,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6490,7 +6779,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6503,7 +6792,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6540,14 +6829,14 @@ def test_create_dialog_node_all_params(self): user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -6559,7 +6848,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6589,11 +6878,13 @@ def test_create_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6608,7 +6899,7 @@ def test_create_dialog_node_required_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6618,13 +6909,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6637,7 +6928,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6650,7 +6941,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6685,7 +6976,7 @@ def test_create_dialog_node_required_params(self): digress_out_slots=digress_out_slots, user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -6700,7 +6991,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6730,11 +7021,13 @@ def test_create_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6749,7 +7042,7 @@ def test_create_dialog_node_value_error(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6759,13 +7052,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6778,7 +7071,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6791,7 +7084,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6810,7 +7103,7 @@ def test_create_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_dialog_node(**req_copy) @@ -6823,7 +7116,8 @@ def test_create_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_create_dialog_node_value_error() -class TestGetDialogNode(): + +class TestGetDialogNode: """ Test Class for get_dialog_node """ @@ -6836,11 +7130,13 @@ def test_get_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6852,14 +7148,14 @@ def test_get_dialog_node_all_params(self): workspace_id, dialog_node, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -6880,11 +7176,13 @@ def test_get_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6894,7 +7192,7 @@ def test_get_dialog_node_required_params(self): response = _service.get_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -6918,11 +7216,13 @@ def test_get_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6934,7 +7234,7 @@ def test_get_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_dialog_node(**req_copy) @@ -6947,7 +7247,8 @@ def test_get_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_get_dialog_node_value_error() -class TestUpdateDialogNode(): + +class TestUpdateDialogNode: """ Test Class for update_dialog_node """ @@ -6960,11 +7261,13 @@ def test_update_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6979,7 +7282,7 @@ def test_update_dialog_node_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6989,13 +7292,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7008,7 +7311,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7022,7 +7325,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7060,14 +7363,14 @@ def test_update_dialog_node_all_params(self): new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -7079,7 +7382,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7109,11 +7412,13 @@ def test_update_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -7128,7 +7433,7 @@ def test_update_dialog_node_required_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -7138,13 +7443,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7157,7 +7462,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7171,7 +7476,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7207,7 +7512,7 @@ def test_update_dialog_node_required_params(self): new_digress_out_slots=new_digress_out_slots, new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -7222,7 +7527,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7252,11 +7557,13 @@ def test_update_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -7271,7 +7578,7 @@ def test_update_dialog_node_value_error(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -7281,13 +7588,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7300,7 +7607,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7314,7 +7621,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7333,7 +7640,7 @@ def test_update_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_dialog_node(**req_copy) @@ -7346,7 +7653,8 @@ def test_update_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_update_dialog_node_value_error() -class TestDeleteDialogNode(): + +class TestDeleteDialogNode: """ Test Class for delete_dialog_node """ @@ -7358,9 +7666,11 @@ def test_delete_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7370,7 +7680,7 @@ def test_delete_dialog_node_all_params(self): response = _service.delete_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -7393,9 +7703,11 @@ def test_delete_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7407,7 +7719,7 @@ def test_delete_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_dialog_node(**req_copy) @@ -7420,6 +7732,7 @@ def test_delete_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_delete_dialog_node_value_error() + # endregion ############################################################################## # End of Service: DialogNodes @@ -7430,7 +7743,8 @@ def test_delete_dialog_node_value_error_with_retries(self): ############################################################################## # region -class TestListLogs(): + +class TestListLogs: """ Test Class for list_logs """ @@ -7443,17 +7757,19 @@ def test_list_logs_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' sort = 'testString' filter = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -7463,14 +7779,14 @@ def test_list_logs_all_params(self): filter=filter, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'sort={}'.format(sort) in query_string assert 'filter={}'.format(filter) in query_string @@ -7494,11 +7810,13 @@ def test_list_logs_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7506,7 +7824,7 @@ def test_list_logs_required_params(self): # Invoke method response = _service.list_logs( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -7530,11 +7848,13 @@ def test_list_logs_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7544,7 +7864,7 @@ def test_list_logs_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_logs(**req_copy) @@ -7557,7 +7877,8 @@ def test_list_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_logs_value_error() -class TestListAllLogs(): + +class TestListAllLogs: """ Test Class for list_all_logs """ @@ -7570,16 +7891,18 @@ def test_list_all_logs_all_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' sort = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -7588,14 +7911,14 @@ def test_list_all_logs_all_params(self): sort=sort, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'sort={}'.format(sort) in query_string @@ -7619,11 +7942,13 @@ def test_list_all_logs_required_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -7631,14 +7956,14 @@ def test_list_all_logs_required_params(self): # Invoke method response = _service.list_all_logs( filter, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string @@ -7659,11 +7984,13 @@ def test_list_all_logs_value_error(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -7673,7 +8000,7 @@ def test_list_all_logs_value_error(self): "filter": filter, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_all_logs(**req_copy) @@ -7686,6 +8013,7 @@ def test_list_all_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_all_logs_value_error() + # endregion ############################################################################## # End of Service: Logs @@ -7696,7 +8024,8 @@ def test_list_all_logs_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -7708,9 +8037,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7718,14 +8049,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -7745,9 +8076,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7757,7 +8090,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -7770,6 +8103,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -7780,7 +8114,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + + +class TestModel_AgentAvailabilityMessage: """ Test Class for AgentAvailabilityMessage """ @@ -7809,7 +8145,8 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_BulkClassifyOutput(): + +class TestModel_BulkClassifyOutput: """ Test Class for BulkClassifyOutput """ @@ -7821,14 +8158,14 @@ def test_bulk_classify_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7856,14 +8193,14 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7873,7 +8210,7 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -7898,7 +8235,8 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestModel_BulkClassifyResponse(): + +class TestModel_BulkClassifyResponse: """ Test Class for BulkClassifyResponse """ @@ -7910,14 +8248,14 @@ def test_bulk_classify_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7945,14 +8283,14 @@ def test_bulk_classify_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7962,11 +8300,11 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model bulk_classify_output_model['entities'] = [runtime_entity_model] bulk_classify_output_model['intents'] = [runtime_intent_model] @@ -7990,7 +8328,8 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestModel_BulkClassifyUtterance(): + +class TestModel_BulkClassifyUtterance: """ Test Class for BulkClassifyUtterance """ @@ -8019,7 +8358,8 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestModel_CaptureGroup(): + +class TestModel_CaptureGroup: """ Test Class for CaptureGroup """ @@ -8049,7 +8389,8 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestModel_ChannelTransferInfo(): + +class TestModel_ChannelTransferInfo: """ Test Class for ChannelTransferInfo """ @@ -8061,10 +8402,10 @@ def test_channel_transfer_info_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model # Construct a json representation of a ChannelTransferInfo model @@ -8086,7 +8427,8 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestModel_ChannelTransferTarget(): + +class TestModel_ChannelTransferTarget: """ Test Class for ChannelTransferTarget """ @@ -8098,7 +8440,7 @@ def test_channel_transfer_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' # Construct a json representation of a ChannelTransferTarget model @@ -8120,7 +8462,8 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestModel_ChannelTransferTargetChat(): + +class TestModel_ChannelTransferTargetChat: """ Test Class for ChannelTransferTargetChat """ @@ -8149,7 +8492,8 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestModel_Context(): + +class TestModel_Context: """ Test Class for Context """ @@ -8161,14 +8505,14 @@ def test_context_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {'foo': 'bar'} + context_model_json['system'] = {'anyKey': 'anyValue'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -8197,7 +8541,8 @@ def test_context_serialization(self): actual_dict = context_model.get_properties() assert actual_dict == expected_dict -class TestModel_Counterexample(): + +class TestModel_Counterexample: """ Test Class for Counterexample """ @@ -8226,7 +8571,8 @@ def test_counterexample_serialization(self): counterexample_model_json2 = counterexample_model.to_dict() assert counterexample_model_json2 == counterexample_model_json -class TestModel_CounterexampleCollection(): + +class TestModel_CounterexampleCollection: """ Test Class for CounterexampleCollection """ @@ -8238,10 +8584,10 @@ def test_counterexample_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8269,7 +8615,8 @@ def test_counterexample_collection_serialization(self): counterexample_collection_model_json2 = counterexample_collection_model.to_dict() assert counterexample_collection_model_json2 == counterexample_collection_model_json -class TestModel_CreateEntity(): + +class TestModel_CreateEntity: """ Test Class for CreateEntity """ @@ -8281,9 +8628,9 @@ def test_create_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - create_value_model = {} # CreateValue + create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -8292,7 +8639,7 @@ def test_create_entity_serialization(self): create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {'foo': 'bar'} + create_entity_model_json['metadata'] = {'anyKey': 'anyValue'} create_entity_model_json['fuzzy_match'] = True create_entity_model_json['values'] = [create_value_model] @@ -8311,7 +8658,8 @@ def test_create_entity_serialization(self): create_entity_model_json2 = create_entity_model.to_dict() assert create_entity_model_json2 == create_entity_model_json -class TestModel_CreateIntent(): + +class TestModel_CreateIntent: """ Test Class for CreateIntent """ @@ -8323,11 +8671,11 @@ def test_create_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] @@ -8352,7 +8700,8 @@ def test_create_intent_serialization(self): create_intent_model_json2 = create_intent_model.to_dict() assert create_intent_model_json2 == create_intent_model_json -class TestModel_CreateValue(): + +class TestModel_CreateValue: """ Test Class for CreateValue """ @@ -8365,7 +8714,7 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {'foo': 'bar'} + create_value_model_json['metadata'] = {'anyKey': 'anyValue'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] @@ -8385,7 +8734,8 @@ def test_create_value_serialization(self): create_value_model_json2 = create_value_model.to_dict() assert create_value_model_json2 == create_value_model_json -class TestModel_DialogNode(): + +class TestModel_DialogNode: """ Test Class for DialogNode """ @@ -8397,41 +8747,41 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -8444,7 +8794,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {'foo': 'bar'} + dialog_node_model_json['metadata'] = {'anyKey': 'anyValue'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -8472,7 +8822,8 @@ def test_dialog_node_serialization(self): dialog_node_model_json2 = dialog_node_model.to_dict() assert dialog_node_model_json2 == dialog_node_model_json -class TestModel_DialogNodeAction(): + +class TestModel_DialogNodeAction: """ Test Class for DialogNodeAction """ @@ -8486,7 +8837,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'foo': 'bar'} + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -8505,7 +8856,8 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestModel_DialogNodeCollection(): + +class TestModel_DialogNodeCollection: """ Test Class for DialogNodeCollection """ @@ -8517,45 +8869,45 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -8563,7 +8915,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -8576,7 +8928,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8604,7 +8956,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_collection_model_json2 = dialog_node_collection_model.to_dict() assert dialog_node_collection_model_json2 == dialog_node_collection_model_json -class TestModel_DialogNodeContext(): + +class TestModel_DialogNodeContext: """ Test Class for DialogNodeContext """ @@ -8616,7 +8969,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -8644,7 +8997,8 @@ def test_dialog_node_context_serialization(self): actual_dict = dialog_node_context_model.get_properties() assert actual_dict == expected_dict -class TestModel_DialogNodeNextStep(): + +class TestModel_DialogNodeNextStep: """ Test Class for DialogNodeNextStep """ @@ -8675,7 +9029,8 @@ def test_dialog_node_next_step_serialization(self): dialog_node_next_step_model_json2 = dialog_node_next_step_model.to_dict() assert dialog_node_next_step_model_json2 == dialog_node_next_step_model_json -class TestModel_DialogNodeOutput(): + +class TestModel_DialogNodeOutput: """ Test Class for DialogNodeOutput """ @@ -8687,26 +9042,26 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8735,7 +9090,8 @@ def test_dialog_node_output_serialization(self): actual_dict = dialog_node_output_model.get_properties() assert actual_dict == expected_dict -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -8747,7 +9103,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8764,7 +9120,8 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestModel_DialogNodeOutputModifiers(): + +class TestModel_DialogNodeOutputModifiers: """ Test Class for DialogNodeOutputModifiers """ @@ -8793,7 +9150,8 @@ def test_dialog_node_output_modifiers_serialization(self): dialog_node_output_modifiers_model_json2 = dialog_node_output_modifiers_model.to_dict() assert dialog_node_output_modifiers_model_json2 == dialog_node_output_modifiers_model_json -class TestModel_DialogNodeOutputOptionsElement(): + +class TestModel_DialogNodeOutputOptionsElement: """ Test Class for DialogNodeOutputOptionsElement """ @@ -8805,21 +9163,21 @@ def test_dialog_node_output_options_element_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8847,14 +9205,14 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8864,7 +9222,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] @@ -8889,7 +9247,8 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): + +class TestModel_DialogNodeOutputOptionsElementValue: """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -8901,21 +9260,21 @@ def test_dialog_node_output_options_element_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8943,14 +9302,14 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8981,7 +9340,8 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodeOutputTextValuesElement(): + +class TestModel_DialogNodeOutputTextValuesElement: """ Test Class for DialogNodeOutputTextValuesElement """ @@ -9010,7 +9370,8 @@ def test_dialog_node_output_text_values_element_serialization(self): dialog_node_output_text_values_element_model_json2 = dialog_node_output_text_values_element_model.to_dict() assert dialog_node_output_text_values_element_model_json2 == dialog_node_output_text_values_element_model_json -class TestModel_DialogNodeVisitedDetails(): + +class TestModel_DialogNodeVisitedDetails: """ Test Class for DialogNodeVisitedDetails """ @@ -9041,7 +9402,8 @@ def test_dialog_node_visited_details_serialization(self): dialog_node_visited_details_model_json2 = dialog_node_visited_details_model.to_dict() assert dialog_node_visited_details_model_json2 == dialog_node_visited_details_model_json -class TestModel_DialogSuggestion(): + +class TestModel_DialogSuggestion: """ Test Class for DialogSuggestion """ @@ -9053,21 +9415,21 @@ def test_dialog_suggestion_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9095,14 +9457,14 @@ def test_dialog_suggestion_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9112,7 +9474,7 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] @@ -9121,7 +9483,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'foo': 'bar'} + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -9139,7 +9501,8 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_DialogSuggestionValue(): + +class TestModel_DialogSuggestionValue: """ Test Class for DialogSuggestionValue """ @@ -9151,21 +9514,21 @@ def test_dialog_suggestion_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9193,14 +9556,14 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9231,7 +9594,8 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_Entity(): + +class TestModel_Entity: """ Test Class for Entity """ @@ -9243,9 +9607,9 @@ def test_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -9254,7 +9618,7 @@ def test_entity_serialization(self): entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {'foo': 'bar'} + entity_model_json['metadata'] = {'anyKey': 'anyValue'} entity_model_json['fuzzy_match'] = True entity_model_json['values'] = [value_model] @@ -9273,7 +9637,8 @@ def test_entity_serialization(self): entity_model_json2 = entity_model.to_dict() assert entity_model_json2 == entity_model_json -class TestModel_EntityCollection(): + +class TestModel_EntityCollection: """ Test Class for EntityCollection """ @@ -9285,21 +9650,21 @@ def test_entity_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9327,7 +9692,8 @@ def test_entity_collection_serialization(self): entity_collection_model_json2 = entity_collection_model.to_dict() assert entity_collection_model_json2 == entity_collection_model_json -class TestModel_EntityMention(): + +class TestModel_EntityMention: """ Test Class for EntityMention """ @@ -9358,7 +9724,8 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestModel_EntityMentionCollection(): + +class TestModel_EntityMentionCollection: """ Test Class for EntityMentionCollection """ @@ -9370,12 +9737,12 @@ def test_entity_mention_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['intent'] = 'testString' entity_mention_model['location'] = [38] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9403,7 +9770,8 @@ def test_entity_mention_collection_serialization(self): entity_mention_collection_model_json2 = entity_mention_collection_model.to_dict() assert entity_mention_collection_model_json2 == entity_mention_collection_model_json -class TestModel_Example(): + +class TestModel_Example: """ Test Class for Example """ @@ -9415,7 +9783,7 @@ def test_example_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] @@ -9439,7 +9807,8 @@ def test_example_serialization(self): example_model_json2 = example_model.to_dict() assert example_model_json2 == example_model_json -class TestModel_ExampleCollection(): + +class TestModel_ExampleCollection: """ Test Class for ExampleCollection """ @@ -9451,15 +9820,15 @@ def test_example_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9487,7 +9856,8 @@ def test_example_collection_serialization(self): example_collection_model_json2 = example_collection_model.to_dict() assert example_collection_model_json2 == example_collection_model_json -class TestModel_Intent(): + +class TestModel_Intent: """ Test Class for Intent """ @@ -9499,11 +9869,11 @@ def test_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] @@ -9528,7 +9898,8 @@ def test_intent_serialization(self): intent_model_json2 = intent_model.to_dict() assert intent_model_json2 == intent_model_json -class TestModel_IntentCollection(): + +class TestModel_IntentCollection: """ Test Class for IntentCollection """ @@ -9540,20 +9911,20 @@ def test_intent_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9581,7 +9952,8 @@ def test_intent_collection_serialization(self): intent_collection_model_json2 = intent_collection_model.to_dict() assert intent_collection_model_json2 == intent_collection_model_json -class TestModel_Log(): + +class TestModel_Log: """ Test Class for Log """ @@ -9593,21 +9965,21 @@ def test_log_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9635,14 +10007,14 @@ def test_log_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9652,47 +10024,47 @@ def test_log_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] @@ -9701,7 +10073,7 @@ def test_log_serialization(self): message_request_model['output'] = output_data_model message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] @@ -9735,7 +10107,8 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestModel_LogCollection(): + +class TestModel_LogCollection: """ Test Class for LogCollection """ @@ -9747,21 +10120,21 @@ def test_log_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9789,14 +10162,14 @@ def test_log_collection_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9806,47 +10179,47 @@ def test_log_collection_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] @@ -9855,7 +10228,7 @@ def test_log_collection_serialization(self): message_request_model['output'] = output_data_model message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] @@ -9864,7 +10237,7 @@ def test_log_collection_serialization(self): message_response_model['output'] = output_data_model message_response_model['user_id'] = 'testString' - log_model = {} # Log + log_model = {} # Log log_model['request'] = message_request_model log_model['response'] = message_response_model log_model['log_id'] = 'testString' @@ -9873,7 +10246,7 @@ def test_log_collection_serialization(self): log_model['workspace_id'] = 'testString' log_model['language'] = 'testString' - log_pagination_model = {} # LogPagination + log_pagination_model = {} # LogPagination log_pagination_model['next_url'] = 'testString' log_pagination_model['matched'] = 38 log_pagination_model['next_cursor'] = 'testString' @@ -9898,7 +10271,8 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestModel_LogMessage(): + +class TestModel_LogMessage: """ Test Class for LogMessage """ @@ -9910,7 +10284,7 @@ def test_log_message_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' @@ -9936,7 +10310,8 @@ def test_log_message_serialization(self): log_message_model_json2 = log_message_model.to_dict() assert log_message_model_json2 == log_message_model_json -class TestModel_LogMessageSource(): + +class TestModel_LogMessageSource: """ Test Class for LogMessageSource """ @@ -9966,7 +10341,8 @@ def test_log_message_source_serialization(self): log_message_source_model_json2 = log_message_source_model.to_dict() assert log_message_source_model_json2 == log_message_source_model_json -class TestModel_LogPagination(): + +class TestModel_LogPagination: """ Test Class for LogPagination """ @@ -9997,7 +10373,8 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_Mention(): + +class TestModel_Mention: """ Test Class for Mention """ @@ -10027,7 +10404,8 @@ def test_mention_serialization(self): mention_model_json2 = mention_model.to_dict() assert mention_model_json2 == mention_model_json -class TestModel_MessageContextMetadata(): + +class TestModel_MessageContextMetadata: """ Test Class for MessageContextMetadata """ @@ -10057,7 +10435,8 @@ def test_message_context_metadata_serialization(self): message_context_metadata_model_json2 = message_context_metadata_model.to_dict() assert message_context_metadata_model_json2 == message_context_metadata_model_json -class TestModel_MessageInput(): + +class TestModel_MessageInput: """ Test Class for MessageInput """ @@ -10099,7 +10478,8 @@ def test_message_input_serialization(self): actual_dict = message_input_model.get_properties() assert actual_dict == expected_dict -class TestModel_MessageRequest(): + +class TestModel_MessageRequest: """ Test Class for MessageRequest """ @@ -10111,21 +10491,21 @@ def test_message_request_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10153,14 +10533,14 @@ def test_message_request_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -10170,40 +10550,40 @@ def test_message_request_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] @@ -10235,7 +10615,8 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestModel_MessageResponse(): + +class TestModel_MessageResponse: """ Test Class for MessageResponse """ @@ -10247,21 +10628,21 @@ def test_message_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10289,14 +10670,14 @@ def test_message_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -10306,40 +10687,40 @@ def test_message_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] @@ -10371,7 +10752,8 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestModel_OutputData(): + +class TestModel_OutputData: """ Test Class for OutputData """ @@ -10383,25 +10765,25 @@ def test_output_data_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] @@ -10439,7 +10821,8 @@ def test_output_data_serialization(self): actual_dict = output_data_model.get_properties() assert actual_dict == expected_dict -class TestModel_Pagination(): + +class TestModel_Pagination: """ Test Class for Pagination """ @@ -10473,7 +10856,8 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestModel_ResponseGenericChannel(): + +class TestModel_ResponseGenericChannel: """ Test Class for ResponseGenericChannel """ @@ -10502,7 +10886,8 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_RuntimeEntity(): + +class TestModel_RuntimeEntity: """ Test Class for RuntimeEntity """ @@ -10514,11 +10899,11 @@ def test_runtime_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10546,11 +10931,11 @@ def test_runtime_entity_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' # Construct a json representation of a RuntimeEntity model @@ -10579,7 +10964,8 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_RuntimeEntityAlternative(): + +class TestModel_RuntimeEntityAlternative: """ Test Class for RuntimeEntityAlternative """ @@ -10609,7 +10995,8 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_RuntimeEntityInterpretation(): + +class TestModel_RuntimeEntityInterpretation: """ Test Class for RuntimeEntityInterpretation """ @@ -10663,7 +11050,8 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_RuntimeEntityRole(): + +class TestModel_RuntimeEntityRole: """ Test Class for RuntimeEntityRole """ @@ -10692,7 +11080,8 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_RuntimeIntent(): + +class TestModel_RuntimeIntent: """ Test Class for RuntimeIntent """ @@ -10722,7 +11111,8 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_StatusError(): + +class TestModel_StatusError: """ Test Class for StatusError """ @@ -10751,7 +11141,8 @@ def test_status_error_serialization(self): status_error_model_json2 = status_error_model.to_dict() assert status_error_model_json2 == status_error_model_json -class TestModel_Synonym(): + +class TestModel_Synonym: """ Test Class for Synonym """ @@ -10780,7 +11171,8 @@ def test_synonym_serialization(self): synonym_model_json2 = synonym_model.to_dict() assert synonym_model_json2 == synonym_model_json -class TestModel_SynonymCollection(): + +class TestModel_SynonymCollection: """ Test Class for SynonymCollection """ @@ -10792,10 +11184,10 @@ def test_synonym_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - synonym_model = {} # Synonym + synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10823,7 +11215,8 @@ def test_synonym_collection_serialization(self): synonym_collection_model_json2 = synonym_collection_model.to_dict() assert synonym_collection_model_json2 == synonym_collection_model_json -class TestModel_Value(): + +class TestModel_Value: """ Test Class for Value """ @@ -10836,7 +11229,7 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {'foo': 'bar'} + value_model_json['metadata'] = {'anyKey': 'anyValue'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] @@ -10856,7 +11249,8 @@ def test_value_serialization(self): value_model_json2 = value_model.to_dict() assert value_model_json2 == value_model_json -class TestModel_ValueCollection(): + +class TestModel_ValueCollection: """ Test Class for ValueCollection """ @@ -10868,14 +11262,14 @@ def test_value_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10903,7 +11297,8 @@ def test_value_collection_serialization(self): value_collection_model_json2 = value_collection_model.to_dict() assert value_collection_model_json2 == value_collection_model_json -class TestModel_Webhook(): + +class TestModel_Webhook: """ Test Class for Webhook """ @@ -10915,7 +11310,7 @@ def test_webhook_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -10940,7 +11335,8 @@ def test_webhook_serialization(self): webhook_model_json2 = webhook_model.to_dict() assert webhook_model_json2 == webhook_model_json -class TestModel_WebhookHeader(): + +class TestModel_WebhookHeader: """ Test Class for WebhookHeader """ @@ -10970,7 +11366,8 @@ def test_webhook_header_serialization(self): webhook_header_model_json2 = webhook_header_model.to_dict() assert webhook_header_model_json2 == webhook_header_model_json -class TestModel_Workspace(): + +class TestModel_Workspace: """ Test Class for Workspace """ @@ -10982,45 +11379,45 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -11028,7 +11425,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11041,13 +11438,13 @@ def test_workspace_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11056,19 +11453,19 @@ def test_workspace_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11076,39 +11473,39 @@ def test_workspace_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] @@ -11119,7 +11516,7 @@ def test_workspace_serialization(self): workspace_model_json['language'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['metadata'] = {'foo': 'bar'} + workspace_model_json['metadata'] = {'anyKey': 'anyValue'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model workspace_model_json['webhooks'] = [webhook_model] @@ -11141,7 +11538,8 @@ def test_workspace_serialization(self): workspace_model_json2 = workspace_model.to_dict() assert workspace_model_json2 == workspace_model_json -class TestModel_WorkspaceCollection(): + +class TestModel_WorkspaceCollection: """ Test Class for WorkspaceCollection """ @@ -11153,45 +11551,45 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -11199,7 +11597,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11212,13 +11610,13 @@ def test_workspace_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11227,19 +11625,19 @@ def test_workspace_collection_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11247,56 +11645,56 @@ def test_workspace_collection_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] - workspace_model = {} # Workspace + workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' workspace_model['language'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['metadata'] = {'foo': 'bar'} + workspace_model['metadata'] = {'anyKey': 'anyValue'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -11324,7 +11722,8 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json -class TestModel_WorkspaceCounts(): + +class TestModel_WorkspaceCounts: """ Test Class for WorkspaceCounts """ @@ -11355,7 +11754,8 @@ def test_workspace_counts_serialization(self): workspace_counts_model_json2 = workspace_counts_model.to_dict() assert workspace_counts_model_json2 == workspace_counts_model_json -class TestModel_WorkspaceSystemSettings(): + +class TestModel_WorkspaceSystemSettings: """ Test Class for WorkspaceSystemSettings """ @@ -11367,10 +11767,10 @@ def test_workspace_system_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11379,20 +11779,20 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model_json['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model @@ -11425,7 +11825,8 @@ def test_workspace_system_settings_serialization(self): actual_dict = workspace_system_settings_model.get_properties() assert actual_dict == expected_dict -class TestModel_WorkspaceSystemSettingsDisambiguation(): + +class TestModel_WorkspaceSystemSettingsDisambiguation: """ Test Class for WorkspaceSystemSettingsDisambiguation """ @@ -11460,7 +11861,8 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json -class TestModel_WorkspaceSystemSettingsNlp(): + +class TestModel_WorkspaceSystemSettingsNlp: """ Test Class for WorkspaceSystemSettingsNlp """ @@ -11489,7 +11891,8 @@ def test_workspace_system_settings_nlp_serialization(self): workspace_system_settings_nlp_model_json2 = workspace_system_settings_nlp_model.to_dict() assert workspace_system_settings_nlp_model_json2 == workspace_system_settings_nlp_model_json -class TestModel_WorkspaceSystemSettingsOffTopic(): + +class TestModel_WorkspaceSystemSettingsOffTopic: """ Test Class for WorkspaceSystemSettingsOffTopic """ @@ -11518,7 +11921,8 @@ def test_workspace_system_settings_off_topic_serialization(self): workspace_system_settings_off_topic_model_json2 = workspace_system_settings_off_topic_model.to_dict() assert workspace_system_settings_off_topic_model_json2 == workspace_system_settings_off_topic_model_json -class TestModel_WorkspaceSystemSettingsSystemEntities(): + +class TestModel_WorkspaceSystemSettingsSystemEntities: """ Test Class for WorkspaceSystemSettingsSystemEntities """ @@ -11547,7 +11951,8 @@ def test_workspace_system_settings_system_entities_serialization(self): workspace_system_settings_system_entities_model_json2 = workspace_system_settings_system_entities_model.to_dict() assert workspace_system_settings_system_entities_model_json2 == workspace_system_settings_system_entities_model_json -class TestModel_WorkspaceSystemSettingsTooling(): + +class TestModel_WorkspaceSystemSettingsTooling: """ Test Class for WorkspaceSystemSettingsTooling """ @@ -11576,7 +11981,8 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio """ @@ -11588,7 +11994,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model @@ -11598,7 +12004,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation @@ -11616,7 +12022,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_audio_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_audio_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer """ @@ -11628,16 +12035,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model @@ -11662,7 +12069,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent """ @@ -11674,13 +12082,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent model @@ -11707,7 +12115,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe """ @@ -11719,7 +12128,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe model @@ -11746,7 +12155,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_iframe_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage """ @@ -11758,7 +12168,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model @@ -11785,7 +12195,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_image_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_image_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption """ @@ -11797,21 +12208,21 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -11839,14 +12250,14 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -11856,16 +12267,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption model @@ -11892,7 +12303,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_option_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_option_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypePause """ @@ -11904,7 +12316,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypePause model @@ -11929,7 +12341,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_pause_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_pause_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill """ @@ -11941,7 +12354,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill model @@ -11968,7 +12381,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_search_skill_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeText """ @@ -11980,10 +12394,10 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model @@ -11991,7 +12405,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' - dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\n' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\\n' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation @@ -12009,7 +12423,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined """ @@ -12021,13 +12436,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -12045,7 +12460,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo """ @@ -12057,7 +12473,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo model @@ -12067,7 +12483,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation @@ -12085,7 +12501,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_video_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_video_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio """ @@ -12097,7 +12514,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model @@ -12107,7 +12524,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -12125,7 +12542,8 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -12137,16 +12555,16 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model @@ -12171,7 +12589,8 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -12183,13 +12602,13 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model @@ -12218,7 +12637,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe """ @@ -12230,7 +12650,7 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model @@ -12257,7 +12677,8 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -12269,7 +12690,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model @@ -12296,7 +12717,8 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -12308,21 +12730,21 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -12350,14 +12772,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -12367,16 +12789,16 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model @@ -12403,7 +12825,8 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause: """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -12415,7 +12838,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model @@ -12440,7 +12863,8 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -12452,21 +12876,21 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -12494,14 +12918,14 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -12511,18 +12935,18 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] - dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'foo': 'bar'} + dialog_suggestion_model['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model['dialog_node'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model @@ -12547,7 +12971,8 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -12559,7 +12984,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model @@ -12583,7 +13008,8 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ @@ -12595,13 +13021,13 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -12619,7 +13045,8 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo """ @@ -12631,7 +13058,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model @@ -12641,7 +13068,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index f0a15e81..181ca3b5 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -71,7 +70,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestCreateAssistant(): + +class TestCreateAssistant: """ Test Class for create_assistant """ @@ -84,11 +84,13 @@ def test_create_assistant_all_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'testString' @@ -100,7 +102,7 @@ def test_create_assistant_all_params(self): language=language, name=name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -129,16 +131,17 @@ def test_create_assistant_required_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.create_assistant() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -160,17 +163,19 @@ def test_create_assistant_value_error(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_assistant(**req_copy) @@ -183,7 +188,8 @@ def test_create_assistant_value_error_with_retries(self): _service.disable_retries() self.test_create_assistant_value_error() -class TestListAssistants(): + +class TestListAssistants: """ Test Class for list_assistants """ @@ -196,14 +202,16 @@ def test_list_assistants_all_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -216,14 +224,14 @@ def test_list_assistants_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -248,16 +256,17 @@ def test_list_assistants_required_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_assistants() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -279,17 +288,19 @@ def test_list_assistants_value_error(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_assistants(**req_copy) @@ -302,7 +313,8 @@ def test_list_assistants_value_error_with_retries(self): _service.disable_retries() self.test_list_assistants_value_error() -class TestDeleteAssistant(): + +class TestDeleteAssistant: """ Test Class for delete_assistant """ @@ -314,9 +326,11 @@ def test_delete_assistant_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -324,7 +338,7 @@ def test_delete_assistant_all_params(self): # Invoke method response = _service.delete_assistant( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -347,9 +361,11 @@ def test_delete_assistant_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -359,7 +375,7 @@ def test_delete_assistant_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_assistant(**req_copy) @@ -372,6 +388,7 @@ def test_delete_assistant_value_error_with_retries(self): _service.disable_retries() self.test_delete_assistant_value_error() + # endregion ############################################################################## # End of Service: Assistants @@ -382,7 +399,8 @@ def test_delete_assistant_value_error_with_retries(self): ############################################################################## # region -class TestCreateSession(): + +class TestCreateSession: """ Test Class for create_session """ @@ -395,11 +413,13 @@ def test_create_session_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a RequestAnalytics model request_analytics_model = {} @@ -415,7 +435,7 @@ def test_create_session_all_params(self): response = _service.create_session( assistant_id, analytics=analytics, - headers={} + headers={}, ) # Check for correct operation @@ -442,11 +462,13 @@ def test_create_session_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values assistant_id = 'testString' @@ -454,7 +476,7 @@ def test_create_session_required_params(self): # Invoke method response = _service.create_session( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -478,11 +500,13 @@ def test_create_session_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values assistant_id = 'testString' @@ -492,7 +516,7 @@ def test_create_session_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_session(**req_copy) @@ -505,7 +529,8 @@ def test_create_session_value_error_with_retries(self): _service.disable_retries() self.test_create_session_value_error() -class TestDeleteSession(): + +class TestDeleteSession: """ Test Class for delete_session """ @@ -517,9 +542,11 @@ def test_delete_session_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -529,7 +556,7 @@ def test_delete_session_all_params(self): response = _service.delete_session( assistant_id, session_id, - headers={} + headers={}, ) # Check for correct operation @@ -552,9 +579,11 @@ def test_delete_session_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -566,7 +595,7 @@ def test_delete_session_value_error(self): "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_session(**req_copy) @@ -579,6 +608,7 @@ def test_delete_session_value_error_with_retries(self): _service.disable_retries() self.test_delete_session_value_error() + # endregion ############################################################################## # End of Service: Sessions @@ -589,7 +619,8 @@ def test_delete_session_value_error_with_retries(self): ############################################################################## # region -class TestMessage(): + +class TestMessage: """ Test Class for message """ @@ -601,12 +632,14 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a RuntimeIntent model runtime_intent_model = {} @@ -689,6 +722,7 @@ def test_message_all_params(self): message_input_options_model = {} message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -725,28 +759,28 @@ def test_message_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkillDialog model - message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - # Construct a dict representation of a MessageContextSkillAction model - message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} # Construct a dict representation of a MessageContextSkills model message_context_skills_model = {} - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model # Construct a dict representation of a MessageContext model message_context_model = {} message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' @@ -762,7 +796,7 @@ def test_message_all_params(self): input=input, context=context, user_id=user_id, - headers={} + headers={}, ) # Check for correct operation @@ -790,12 +824,14 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -805,7 +841,7 @@ def test_message_required_params(self): response = _service.message( assistant_id, session_id, - headers={} + headers={}, ) # Check for correct operation @@ -828,12 +864,14 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -845,7 +883,7 @@ def test_message_value_error(self): "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message(**req_copy) @@ -858,7 +896,8 @@ def test_message_value_error_with_retries(self): _service.disable_retries() self.test_message_value_error() -class TestMessageStateless(): + +class TestMessageStateless: """ Test Class for message_stateless """ @@ -870,12 +909,14 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a RuntimeIntent model runtime_intent_model = {} @@ -954,23 +995,24 @@ def test_message_stateless_all_params(self): message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - # Construct a dict representation of a MessageInputOptionsStateless model - message_input_options_stateless_model = {} - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False - - # Construct a dict representation of a MessageInputStateless model - message_input_stateless_model = {} - message_input_stateless_model['message_type'] = 'text' - message_input_stateless_model['text'] = 'testString' - message_input_stateless_model['intents'] = [runtime_intent_model] - message_input_stateless_model['entities'] = [runtime_entity_model] - message_input_stateless_model['suggestion_id'] = 'testString' - message_input_stateless_model['attachments'] = [message_input_attachment_model] - message_input_stateless_model['analytics'] = request_analytics_model - message_input_stateless_model['options'] = message_input_options_stateless_model + # Construct a dict representation of a StatelessMessageInputOptions model + stateless_message_input_options_model = {} + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a dict representation of a StatelessMessageInput model + stateless_message_input_model = {} + stateless_message_input_model['message_type'] = 'text' + stateless_message_input_model['text'] = 'testString' + stateless_message_input_model['intents'] = [runtime_intent_model] + stateless_message_input_model['entities'] = [runtime_entity_model] + stateless_message_input_model['suggestion_id'] = 'testString' + stateless_message_input_model['attachments'] = [message_input_attachment_model] + stateless_message_input_model['analytics'] = request_analytics_model + stateless_message_input_model['options'] = stateless_message_input_options_model # Construct a dict representation of a MessageContextGlobalSystem model message_context_global_system_model = {} @@ -983,43 +1025,45 @@ def test_message_stateless_all_params(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - # Construct a dict representation of a MessageContextGlobalStateless model - message_context_global_stateless_model = {} - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + # Construct a dict representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model = {} + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' # Construct a dict representation of a MessageContextSkillSystem model message_context_skill_system_model = {} message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkillDialog model - message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model - - # Construct a dict representation of a MessageContextSkillAction model - message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - - # Construct a dict representation of a MessageContextSkills model - message_context_skills_model = {} - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model - - # Construct a dict representation of a MessageContextStateless model - message_context_stateless_model = {} - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'foo': 'bar'} + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model = {} + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model = {} + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a dict representation of a StatelessMessageContext model + stateless_message_context_model = {} + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' - input = message_input_stateless_model - context = message_context_stateless_model + input = stateless_message_input_model + context = stateless_message_context_model user_id = 'testString' # Invoke method @@ -1028,7 +1072,7 @@ def test_message_stateless_all_params(self): input=input, context=context, user_id=user_id, - headers={} + headers={}, ) # Check for correct operation @@ -1036,8 +1080,8 @@ def test_message_stateless_all_params(self): assert response.status_code == 200 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == message_input_stateless_model - assert req_body['context'] == message_context_stateless_model + assert req_body['input'] == stateless_message_input_model + assert req_body['context'] == stateless_message_context_model assert req_body['user_id'] == 'testString' def test_message_stateless_all_params_with_retries(self): @@ -1056,12 +1100,14 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1069,7 +1115,7 @@ def test_message_stateless_required_params(self): # Invoke method response = _service.message_stateless( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1092,12 +1138,14 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1107,7 +1155,7 @@ def test_message_stateless_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message_stateless(**req_copy) @@ -1120,6 +1168,7 @@ def test_message_stateless_value_error_with_retries(self): _service.disable_retries() self.test_message_stateless_value_error() + # endregion ############################################################################## # End of Service: Message @@ -1130,7 +1179,8 @@ def test_message_stateless_value_error_with_retries(self): ############################################################################## # region -class TestBulkClassify(): + +class TestBulkClassify: """ Test Class for bulk_classify """ @@ -1143,11 +1193,13 @@ def test_bulk_classify_all_params(self): # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -1161,7 +1213,7 @@ def test_bulk_classify_all_params(self): response = _service.bulk_classify( skill_id, input, - headers={} + headers={}, ) # Check for correct operation @@ -1188,11 +1240,13 @@ def test_bulk_classify_value_error(self): # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -1208,7 +1262,7 @@ def test_bulk_classify_value_error(self): "input": input, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) @@ -1221,6 +1275,7 @@ def test_bulk_classify_value_error_with_retries(self): _service.disable_retries() self.test_bulk_classify_value_error() + # endregion ############################################################################## # End of Service: BulkClassify @@ -1231,7 +1286,8 @@ def test_bulk_classify_value_error_with_retries(self): ############################################################################## # region -class TestListLogs(): + +class TestListLogs: """ Test Class for list_logs """ @@ -1243,18 +1299,20 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' sort = 'testString' filter = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -1264,14 +1322,14 @@ def test_list_logs_all_params(self): filter=filter, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'sort={}'.format(sort) in query_string assert 'filter={}'.format(filter) in query_string @@ -1294,12 +1352,14 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1307,7 +1367,7 @@ def test_list_logs_required_params(self): # Invoke method response = _service.list_logs( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1330,12 +1390,14 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1345,7 +1407,7 @@ def test_list_logs_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_logs(**req_copy) @@ -1358,6 +1420,7 @@ def test_list_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_logs_value_error() + # endregion ############################################################################## # End of Service: Logs @@ -1368,7 +1431,8 @@ def test_list_logs_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -1380,9 +1444,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -1390,14 +1456,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -1417,9 +1483,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -1429,7 +1497,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -1442,6 +1510,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -1452,7 +1521,8 @@ def test_delete_user_data_value_error_with_retries(self): ############################################################################## # region -class TestListEnvironments(): + +class TestListEnvironments: """ Test Class for list_environments """ @@ -1465,15 +1535,17 @@ def test_list_environments_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -1487,14 +1559,14 @@ def test_list_environments_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -1519,11 +1591,13 @@ def test_list_environments_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1531,7 +1605,7 @@ def test_list_environments_required_params(self): # Invoke method response = _service.list_environments( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1555,11 +1629,13 @@ def test_list_environments_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1569,7 +1645,7 @@ def test_list_environments_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_environments(**req_copy) @@ -1582,7 +1658,8 @@ def test_list_environments_value_error_with_retries(self): _service.disable_retries() self.test_list_environments_value_error() -class TestGetEnvironment(): + +class TestGetEnvironment: """ Test Class for get_environment """ @@ -1595,11 +1672,13 @@ def test_get_environment_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1611,14 +1690,14 @@ def test_get_environment_all_params(self): assistant_id, environment_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1639,11 +1718,13 @@ def test_get_environment_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1653,7 +1734,7 @@ def test_get_environment_required_params(self): response = _service.get_environment( assistant_id, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1677,11 +1758,13 @@ def test_get_environment_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1693,7 +1776,7 @@ def test_get_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_environment(**req_copy) @@ -1706,7 +1789,8 @@ def test_get_environment_value_error_with_retries(self): _service.disable_retries() self.test_get_environment_value_error() -class TestUpdateEnvironment(): + +class TestUpdateEnvironment: """ Test Class for update_environment """ @@ -1719,11 +1803,17 @@ def test_update_environment_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model = {} + base_environment_orchestration_model['search_skill_fallback'] = True # Construct a dict representation of a EnvironmentSkill model environment_skill_model = {} @@ -1738,6 +1828,7 @@ def test_update_environment_all_params(self): environment_id = 'testString' name = 'testString' description = 'testString' + orchestration = base_environment_orchestration_model session_timeout = 10 skill_references = [environment_skill_model] @@ -1747,9 +1838,10 @@ def test_update_environment_all_params(self): environment_id, name=name, description=description, + orchestration=orchestration, session_timeout=session_timeout, skill_references=skill_references, - headers={} + headers={}, ) # Check for correct operation @@ -1759,6 +1851,7 @@ def test_update_environment_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' + assert req_body['orchestration'] == base_environment_orchestration_model assert req_body['session_timeout'] == 10 assert req_body['skill_references'] == [environment_skill_model] @@ -1779,11 +1872,13 @@ def test_update_environment_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1793,7 +1888,7 @@ def test_update_environment_required_params(self): response = _service.update_environment( assistant_id, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1817,11 +1912,13 @@ def test_update_environment_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1833,7 +1930,7 @@ def test_update_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_environment(**req_copy) @@ -1846,6 +1943,7 @@ def test_update_environment_value_error_with_retries(self): _service.disable_retries() self.test_update_environment_value_error() + # endregion ############################################################################## # End of Service: Environments @@ -1856,7 +1954,8 @@ def test_update_environment_value_error_with_retries(self): ############################################################################## # region -class TestCreateRelease(): + +class TestCreateRelease: """ Test Class for create_release """ @@ -1869,11 +1968,13 @@ def test_create_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1883,7 +1984,7 @@ def test_create_release_all_params(self): response = _service.create_release( assistant_id, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -1910,11 +2011,13 @@ def test_create_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1922,7 +2025,7 @@ def test_create_release_required_params(self): # Invoke method response = _service.create_release( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1946,11 +2049,13 @@ def test_create_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1960,7 +2065,7 @@ def test_create_release_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_release(**req_copy) @@ -1973,7 +2078,8 @@ def test_create_release_value_error_with_retries(self): _service.disable_retries() self.test_create_release_value_error() -class TestListReleases(): + +class TestListReleases: """ Test Class for list_releases """ @@ -1986,15 +2092,17 @@ def test_list_releases_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -2008,14 +2116,14 @@ def test_list_releases_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2040,11 +2148,13 @@ def test_list_releases_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2052,7 +2162,7 @@ def test_list_releases_required_params(self): # Invoke method response = _service.list_releases( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -2076,11 +2186,13 @@ def test_list_releases_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2090,7 +2202,7 @@ def test_list_releases_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_releases(**req_copy) @@ -2103,7 +2215,8 @@ def test_list_releases_value_error_with_retries(self): _service.disable_retries() self.test_list_releases_value_error() -class TestGetRelease(): + +class TestGetRelease: """ Test Class for get_release """ @@ -2116,11 +2229,13 @@ def test_get_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2132,14 +2247,14 @@ def test_get_release_all_params(self): assistant_id, release, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2160,11 +2275,13 @@ def test_get_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2174,7 +2291,7 @@ def test_get_release_required_params(self): response = _service.get_release( assistant_id, release, - headers={} + headers={}, ) # Check for correct operation @@ -2198,11 +2315,13 @@ def test_get_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2214,7 +2333,7 @@ def test_get_release_value_error(self): "release": release, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_release(**req_copy) @@ -2227,7 +2346,8 @@ def test_get_release_value_error_with_retries(self): _service.disable_retries() self.test_get_release_value_error() -class TestDeleteRelease(): + +class TestDeleteRelease: """ Test Class for delete_release """ @@ -2239,9 +2359,11 @@ def test_delete_release_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2251,7 +2373,7 @@ def test_delete_release_all_params(self): response = _service.delete_release( assistant_id, release, - headers={} + headers={}, ) # Check for correct operation @@ -2274,9 +2396,11 @@ def test_delete_release_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2288,7 +2412,7 @@ def test_delete_release_value_error(self): "release": release, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_release(**req_copy) @@ -2301,7 +2425,8 @@ def test_delete_release_value_error_with_retries(self): _service.disable_retries() self.test_delete_release_value_error() -class TestDeployRelease(): + +class TestDeployRelease: """ Test Class for deploy_release """ @@ -2314,11 +2439,13 @@ def test_deploy_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2332,14 +2459,14 @@ def test_deploy_release_all_params(self): release, environment_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2363,11 +2490,13 @@ def test_deploy_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2379,7 +2508,7 @@ def test_deploy_release_required_params(self): assistant_id, release, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -2406,11 +2535,13 @@ def test_deploy_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2424,7 +2555,7 @@ def test_deploy_release_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.deploy_release(**req_copy) @@ -2437,6 +2568,7 @@ def test_deploy_release_value_error_with_retries(self): _service.disable_retries() self.test_deploy_release_value_error() + # endregion ############################################################################## # End of Service: Releases @@ -2447,7 +2579,8 @@ def test_deploy_release_value_error_with_retries(self): ############################################################################## # region -class TestGetSkill(): + +class TestGetSkill: """ Test Class for get_skill """ @@ -2460,11 +2593,13 @@ def test_get_skill_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2474,7 +2609,7 @@ def test_get_skill_all_params(self): response = _service.get_skill( assistant_id, skill_id, - headers={} + headers={}, ) # Check for correct operation @@ -2498,11 +2633,13 @@ def test_get_skill_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2514,7 +2651,7 @@ def test_get_skill_value_error(self): "skill_id": skill_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_skill(**req_copy) @@ -2527,7 +2664,8 @@ def test_get_skill_value_error_with_retries(self): _service.disable_retries() self.test_get_skill_value_error() -class TestUpdateSkill(): + +class TestUpdateSkill: """ Test Class for update_skill """ @@ -2540,11 +2678,13 @@ def test_update_skill_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2586,8 +2726,8 @@ def test_update_skill_all_params(self): skill_id = 'testString' name = 'testString' description = 'testString' - workspace = {'foo': 'bar'} - dialog_settings = {'foo': 'bar'} + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} search_settings = search_settings_model # Invoke method @@ -2599,7 +2739,7 @@ def test_update_skill_all_params(self): workspace=workspace, dialog_settings=dialog_settings, search_settings=search_settings, - headers={} + headers={}, ) # Check for correct operation @@ -2609,8 +2749,8 @@ def test_update_skill_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['workspace'] == {'foo': 'bar'} - assert req_body['dialog_settings'] == {'foo': 'bar'} + assert req_body['workspace'] == {'anyKey': 'anyValue'} + assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} assert req_body['search_settings'] == search_settings_model def test_update_skill_all_params_with_retries(self): @@ -2630,11 +2770,13 @@ def test_update_skill_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2676,8 +2818,8 @@ def test_update_skill_value_error(self): skill_id = 'testString' name = 'testString' description = 'testString' - workspace = {'foo': 'bar'} - dialog_settings = {'foo': 'bar'} + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} search_settings = search_settings_model # Pass in all but one required param and check for a ValueError @@ -2686,7 +2828,7 @@ def test_update_skill_value_error(self): "skill_id": skill_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_skill(**req_copy) @@ -2699,7 +2841,8 @@ def test_update_skill_value_error_with_retries(self): _service.disable_retries() self.test_update_skill_value_error() -class TestExportSkills(): + +class TestExportSkills: """ Test Class for export_skills """ @@ -2712,11 +2855,13 @@ def test_export_skills_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2726,14 +2871,14 @@ def test_export_skills_all_params(self): response = _service.export_skills( assistant_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2754,11 +2899,13 @@ def test_export_skills_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2766,7 +2913,7 @@ def test_export_skills_required_params(self): # Invoke method response = _service.export_skills( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -2790,11 +2937,13 @@ def test_export_skills_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2804,7 +2953,7 @@ def test_export_skills_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.export_skills(**req_copy) @@ -2817,7 +2966,8 @@ def test_export_skills_value_error_with_retries(self): _service.disable_retries() self.test_export_skills_value_error() -class TestImportSkills(): + +class TestImportSkills: """ Test Class for import_skills """ @@ -2830,11 +2980,13 @@ def test_import_skills_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2875,8 +3027,8 @@ def test_import_skills_all_params(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2898,14 +3050,14 @@ def test_import_skills_all_params(self): assistant_skills, assistant_state, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2930,11 +3082,13 @@ def test_import_skills_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2975,8 +3129,8 @@ def test_import_skills_required_params(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2996,7 +3150,7 @@ def test_import_skills_required_params(self): assistant_id, assistant_skills, assistant_state, - headers={} + headers={}, ) # Check for correct operation @@ -3024,11 +3178,13 @@ def test_import_skills_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -3069,8 +3225,8 @@ def test_import_skills_value_error(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -3092,7 +3248,7 @@ def test_import_skills_value_error(self): "assistant_state": assistant_state, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.import_skills(**req_copy) @@ -3105,7 +3261,8 @@ def test_import_skills_value_error_with_retries(self): _service.disable_retries() self.test_import_skills_value_error() -class TestImportSkillsStatus(): + +class TestImportSkillsStatus: """ Test Class for import_skills_status """ @@ -3118,11 +3275,13 @@ def test_import_skills_status_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import/status') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -3130,7 +3289,7 @@ def test_import_skills_status_all_params(self): # Invoke method response = _service.import_skills_status( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -3154,11 +3313,13 @@ def test_import_skills_status_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import/status') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -3168,7 +3329,7 @@ def test_import_skills_status_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.import_skills_status(**req_copy) @@ -3181,6 +3342,7 @@ def test_import_skills_status_value_error_with_retries(self): _service.disable_retries() self.test_import_skills_status_value_error() + # endregion ############################################################################## # End of Service: Skills @@ -3191,7 +3353,9 @@ def test_import_skills_status_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + + +class TestModel_AgentAvailabilityMessage: """ Test Class for AgentAvailabilityMessage """ @@ -3220,7 +3384,8 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_AssistantCollection(): + +class TestModel_AssistantCollection: """ Test Class for AssistantCollection """ @@ -3232,12 +3397,12 @@ def test_assistant_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - assistant_data_model = {} # AssistantData + assistant_data_model = {} # AssistantData assistant_data_model['name'] = 'testString' assistant_data_model['description'] = 'testString' assistant_data_model['language'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -3265,7 +3430,8 @@ def test_assistant_collection_serialization(self): assistant_collection_model_json2 = assistant_collection_model.to_dict() assert assistant_collection_model_json2 == assistant_collection_model_json -class TestModel_AssistantData(): + +class TestModel_AssistantData: """ Test Class for AssistantData """ @@ -3296,7 +3462,8 @@ def test_assistant_data_serialization(self): assistant_data_model_json2 = assistant_data_model.to_dict() assert assistant_data_model_json2 == assistant_data_model_json -class TestModel_AssistantSkill(): + +class TestModel_AssistantSkill: """ Test Class for AssistantSkill """ @@ -3326,7 +3493,8 @@ def test_assistant_skill_serialization(self): assistant_skill_model_json2 = assistant_skill_model.to_dict() assert assistant_skill_model_json2 == assistant_skill_model_json -class TestModel_AssistantState(): + +class TestModel_AssistantState: """ Test Class for AssistantState """ @@ -3356,7 +3524,8 @@ def test_assistant_state_serialization(self): assistant_state_model_json2 = assistant_state_model.to_dict() assert assistant_state_model_json2 == assistant_state_model_json -class TestModel_BaseEnvironmentOrchestration(): + +class TestModel_BaseEnvironmentOrchestration: """ Test Class for BaseEnvironmentOrchestration """ @@ -3385,7 +3554,8 @@ def test_base_environment_orchestration_serialization(self): base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json -class TestModel_BaseEnvironmentReleaseReference(): + +class TestModel_BaseEnvironmentReleaseReference: """ Test Class for BaseEnvironmentReleaseReference """ @@ -3414,7 +3584,8 @@ def test_base_environment_release_reference_serialization(self): base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json -class TestModel_BulkClassifyOutput(): + +class TestModel_BulkClassifyOutput: """ Test Class for BulkClassifyOutput """ @@ -3426,14 +3597,14 @@ def test_bulk_classify_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3461,14 +3632,14 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3479,7 +3650,7 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' @@ -3505,7 +3676,8 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestModel_BulkClassifyResponse(): + +class TestModel_BulkClassifyResponse: """ Test Class for BulkClassifyResponse """ @@ -3517,14 +3689,14 @@ def test_bulk_classify_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3552,14 +3724,14 @@ def test_bulk_classify_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3570,12 +3742,12 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model bulk_classify_output_model['entities'] = [runtime_entity_model] bulk_classify_output_model['intents'] = [runtime_intent_model] @@ -3599,7 +3771,8 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestModel_BulkClassifyUtterance(): + +class TestModel_BulkClassifyUtterance: """ Test Class for BulkClassifyUtterance """ @@ -3628,7 +3801,8 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestModel_CaptureGroup(): + +class TestModel_CaptureGroup: """ Test Class for CaptureGroup """ @@ -3658,7 +3832,8 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestModel_ChannelTransferInfo(): + +class TestModel_ChannelTransferInfo: """ Test Class for ChannelTransferInfo """ @@ -3670,10 +3845,10 @@ def test_channel_transfer_info_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model # Construct a json representation of a ChannelTransferInfo model @@ -3695,7 +3870,8 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestModel_ChannelTransferTarget(): + +class TestModel_ChannelTransferTarget: """ Test Class for ChannelTransferTarget """ @@ -3707,7 +3883,7 @@ def test_channel_transfer_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' # Construct a json representation of a ChannelTransferTarget model @@ -3729,7 +3905,8 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestModel_ChannelTransferTargetChat(): + +class TestModel_ChannelTransferTargetChat: """ Test Class for ChannelTransferTargetChat """ @@ -3758,7 +3935,8 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestModel_DialogLogMessage(): + +class TestModel_DialogLogMessage: """ Test Class for DialogLogMessage """ @@ -3770,7 +3948,7 @@ def test_dialog_log_message_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' @@ -3796,7 +3974,8 @@ def test_dialog_log_message_serialization(self): dialog_log_message_model_json2 = dialog_log_message_model.to_dict() assert dialog_log_message_model_json2 == dialog_log_message_model_json -class TestModel_DialogNodeAction(): + +class TestModel_DialogNodeAction: """ Test Class for DialogNodeAction """ @@ -3810,7 +3989,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'foo': 'bar'} + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -3829,7 +4008,8 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -3841,7 +4021,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -3858,7 +4038,8 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestModel_DialogNodeOutputOptionsElement(): + +class TestModel_DialogNodeOutputOptionsElement: """ Test Class for DialogNodeOutputOptionsElement """ @@ -3870,16 +4051,16 @@ def test_dialog_node_output_options_element_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3907,14 +4088,14 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3925,28 +4106,29 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -3956,7 +4138,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model # Construct a json representation of a DialogNodeOutputOptionsElement model @@ -3979,7 +4161,8 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): + +class TestModel_DialogNodeOutputOptionsElementValue: """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -3991,16 +4174,16 @@ def test_dialog_node_output_options_element_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4028,14 +4211,14 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4046,28 +4229,29 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4096,7 +4280,8 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodeVisited(): + +class TestModel_DialogNodeVisited: """ Test Class for DialogNodeVisited """ @@ -4127,7 +4312,8 @@ def test_dialog_node_visited_serialization(self): dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() assert dialog_node_visited_model_json2 == dialog_node_visited_model_json -class TestModel_DialogSuggestion(): + +class TestModel_DialogSuggestion: """ Test Class for DialogSuggestion """ @@ -4139,16 +4325,16 @@ def test_dialog_suggestion_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4176,14 +4362,14 @@ def test_dialog_suggestion_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4194,28 +4380,29 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4225,14 +4412,14 @@ def test_dialog_suggestion_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model # Construct a json representation of a DialogSuggestion model dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'foo': 'bar'} + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} # Construct a model instance of DialogSuggestion by calling from_dict on the json representation dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) @@ -4249,7 +4436,8 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_DialogSuggestionValue(): + +class TestModel_DialogSuggestionValue: """ Test Class for DialogSuggestionValue """ @@ -4261,16 +4449,16 @@ def test_dialog_suggestion_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4298,14 +4486,14 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4316,28 +4504,29 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4366,7 +4555,8 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_Environment(): + +class TestModel_Environment: """ Test Class for Environment """ @@ -4378,7 +4568,10 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_skill_model = {} # EnvironmentSkill + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' environment_skill_model['disabled'] = True @@ -4389,6 +4582,7 @@ def test_environment_serialization(self): environment_model_json = {} environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' + environment_model_json['orchestration'] = base_environment_orchestration_model environment_model_json['session_timeout'] = 10 environment_model_json['skill_references'] = [environment_skill_model] @@ -4407,7 +4601,8 @@ def test_environment_serialization(self): environment_model_json2 = environment_model.to_dict() assert environment_model_json2 == environment_model_json -class TestModel_EnvironmentCollection(): + +class TestModel_EnvironmentCollection: """ Test Class for EnvironmentCollection """ @@ -4419,20 +4614,24 @@ def test_environment_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_skill_model = {} # EnvironmentSkill + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' environment_skill_model['disabled'] = True environment_skill_model['snapshot'] = 'testString' environment_skill_model['skill_reference'] = 'testString' - environment_model = {} # Environment + environment_model = {} # Environment environment_model['name'] = 'testString' environment_model['description'] = 'testString' + environment_model['orchestration'] = base_environment_orchestration_model environment_model['session_timeout'] = 10 environment_model['skill_references'] = [environment_skill_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -4460,7 +4659,8 @@ def test_environment_collection_serialization(self): environment_collection_model_json2 = environment_collection_model.to_dict() assert environment_collection_model_json2 == environment_collection_model_json -class TestModel_EnvironmentReference(): + +class TestModel_EnvironmentReference: """ Test Class for EnvironmentReference """ @@ -4489,7 +4689,8 @@ def test_environment_reference_serialization(self): environment_reference_model_json2 = environment_reference_model.to_dict() assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_EnvironmentSkill(): + +class TestModel_EnvironmentSkill: """ Test Class for EnvironmentSkill """ @@ -4522,7 +4723,8 @@ def test_environment_skill_serialization(self): environment_skill_model_json2 = environment_skill_model.to_dict() assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_IntegrationReference(): + +class TestModel_IntegrationReference: """ Test Class for IntegrationReference """ @@ -4552,7 +4754,8 @@ def test_integration_reference_serialization(self): integration_reference_model_json2 = integration_reference_model.to_dict() assert integration_reference_model_json2 == integration_reference_model_json -class TestModel_Log(): + +class TestModel_Log: """ Test Class for Log """ @@ -4564,16 +4767,16 @@ def test_log_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4601,14 +4804,14 @@ def test_log_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4619,38 +4822,39 @@ def test_log_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - message_context_global_system_model = {} # MessageContextGlobalSystem + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -4660,74 +4864,74 @@ def test_log_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -4735,37 +4939,37 @@ def test_log_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} - message_output_model['spelling'] = message_output_spelling_model + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' # Construct a json representation of a Log model log_model_json = {} log_model_json['log_id'] = 'testString' - log_model_json['request'] = message_request_model - log_model_json['response'] = message_response_model + log_model_json['request'] = log_request_model + log_model_json['response'] = log_response_model log_model_json['assistant_id'] = 'testString' log_model_json['session_id'] = 'testString' log_model_json['skill_id'] = 'testString' @@ -4790,7 +4994,8 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestModel_LogCollection(): + +class TestModel_LogCollection: """ Test Class for LogCollection """ @@ -4802,16 +5007,16 @@ def test_log_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4839,14 +5044,14 @@ def test_log_collection_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4857,38 +5062,39 @@ def test_log_collection_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - message_context_global_system_model = {} # MessageContextGlobalSystem + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -4898,74 +5104,74 @@ def test_log_collection_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -4973,36 +5179,36 @@ def test_log_collection_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} - message_output_model['spelling'] = message_output_spelling_model - - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' - - log_model = {} # Log + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' + + log_model = {} # Log log_model['log_id'] = 'testString' - log_model['request'] = message_request_model - log_model['response'] = message_response_model + log_model['request'] = log_request_model + log_model['response'] = log_response_model log_model['assistant_id'] = 'testString' log_model['session_id'] = 'testString' log_model['skill_id'] = 'testString' @@ -5012,7 +5218,7 @@ def test_log_collection_serialization(self): log_model['language'] = 'testString' log_model['customer_id'] = 'testString' - log_pagination_model = {} # LogPagination + log_pagination_model = {} # LogPagination log_pagination_model['next_url'] = 'testString' log_pagination_model['matched'] = 38 log_pagination_model['next_cursor'] = 'testString' @@ -5037,7 +5243,8 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestModel_LogPagination(): + +class TestModel_LogPagination: """ Test Class for LogPagination """ @@ -5068,21 +5275,109 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_MessageContext(): + +class TestModel_LogRequest: """ - Test Class for MessageContext + Test Class for LogRequest """ - def test_message_context_serialization(self): + def test_log_request_serialization(self): """ - Test serialization/deserialization for MessageContext + Test serialization/deserialization for LogRequest """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'Hello' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -5090,414 +5385,76 @@ def test_message_context_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'foo': 'bar'} + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False + # Construct a json representation of a LogRequest model + log_request_model_json = {} + log_request_model_json['input'] = log_request_input_model + log_request_model_json['context'] = message_context_model + log_request_model_json['user_id'] = 'testString' - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model = LogRequest.from_dict(log_request_model_json) + assert log_request_model != False + + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ + log_request_model2 = LogRequest(**log_request_model_dict) # Verify the model instances are equivalent - assert message_context_model == message_context_model2 + assert log_request_model == log_request_model2 # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json + log_request_model_json2 = log_request_model.to_dict() + assert log_request_model_json2 == log_request_model_json -class TestModel_MessageContextGlobal(): + +class TestModel_LogRequestInput: """ - Test Class for MessageContextGlobal + Test Class for LogRequestInput """ - def test_message_context_global_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobal - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json - -class TestModel_MessageContextGlobalStateless(): - """ - Test Class for MessageContextGlobalStateless - """ - - def test_message_context_global_stateless_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobalStateless - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - # Construct a json representation of a MessageContextGlobalStateless model - message_context_global_stateless_model_json = {} - message_context_global_stateless_model_json['system'] = message_context_global_system_model - message_context_global_stateless_model_json['session_id'] = 'testString' - - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json) - assert message_context_global_stateless_model != False - - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model_dict = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json).__dict__ - message_context_global_stateless_model2 = MessageContextGlobalStateless(**message_context_global_stateless_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_stateless_model == message_context_global_stateless_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() - assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json - -class TestModel_MessageContextGlobalSystem(): - """ - Test Class for MessageContextGlobalSystem - """ - - def test_message_context_global_system_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobalSystem - """ - - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json - -class TestModel_MessageContextSkillAction(): - """ - Test Class for MessageContextSkillAction - """ - - def test_message_context_skill_action_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillAction - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a MessageContextSkillAction model - message_context_skill_action_model_json = {} - message_context_skill_action_model_json['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model_json['system'] = message_context_skill_system_model - message_context_skill_action_model_json['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model_json['skill_variables'] = {'foo': 'bar'} - - # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation - message_context_skill_action_model = MessageContextSkillAction.from_dict(message_context_skill_action_model_json) - assert message_context_skill_action_model != False - - # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation - message_context_skill_action_model_dict = MessageContextSkillAction.from_dict(message_context_skill_action_model_json).__dict__ - message_context_skill_action_model2 = MessageContextSkillAction(**message_context_skill_action_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_action_model == message_context_skill_action_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_action_model_json2 = message_context_skill_action_model.to_dict() - assert message_context_skill_action_model_json2 == message_context_skill_action_model_json - -class TestModel_MessageContextSkillDialog(): - """ - Test Class for MessageContextSkillDialog - """ - - def test_message_context_skill_dialog_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillDialog - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a MessageContextSkillDialog model - message_context_skill_dialog_model_json = {} - message_context_skill_dialog_model_json['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model_json['system'] = message_context_skill_system_model - - # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation - message_context_skill_dialog_model = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json) - assert message_context_skill_dialog_model != False - - # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation - message_context_skill_dialog_model_dict = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json).__dict__ - message_context_skill_dialog_model2 = MessageContextSkillDialog(**message_context_skill_dialog_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_dialog_model == message_context_skill_dialog_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_dialog_model_json2 = message_context_skill_dialog_model.to_dict() - assert message_context_skill_dialog_model_json2 == message_context_skill_dialog_model_json - -class TestModel_MessageContextSkillSystem(): - """ - Test Class for MessageContextSkillSystem - """ - - def test_message_context_skill_system_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillSystem - """ - - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == expected_dict - -class TestModel_MessageContextSkills(): - """ - Test Class for MessageContextSkills - """ - - def test_message_context_skills_serialization(self): - """ - Test serialization/deserialization for MessageContextSkills - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model - - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - - # Construct a json representation of a MessageContextSkills model - message_context_skills_model_json = {} - message_context_skills_model_json['main skill'] = message_context_skill_dialog_model - message_context_skills_model_json['actions skill'] = message_context_skill_action_model - - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) - assert message_context_skills_model != False - - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ - message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) - - # Verify the model instances are equivalent - assert message_context_skills_model == message_context_skills_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skills_model_json2 = message_context_skills_model.to_dict() - assert message_context_skills_model_json2 == message_context_skills_model_json - -class TestModel_MessageContextStateless(): - """ - Test Class for MessageContextStateless - """ - - def test_message_context_stateless_serialization(self): - """ - Test serialization/deserialization for MessageContextStateless - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model - - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model - - # Construct a json representation of a MessageContextStateless model - message_context_stateless_model_json = {} - message_context_stateless_model_json['global'] = message_context_global_stateless_model - message_context_stateless_model_json['skills'] = message_context_skills_model - message_context_stateless_model_json['integrations'] = {'foo': 'bar'} - - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) - assert message_context_stateless_model != False - - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model_dict = MessageContextStateless.from_dict(message_context_stateless_model_json).__dict__ - message_context_stateless_model2 = MessageContextStateless(**message_context_stateless_model_dict) - - # Verify the model instances are equivalent - assert message_context_stateless_model == message_context_stateless_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_stateless_model_json2 = message_context_stateless_model.to_dict() - assert message_context_stateless_model_json2 == message_context_stateless_model_json - -class TestModel_MessageInput(): - """ - Test Class for MessageInput - """ - - def test_message_input_serialization(self): + def test_log_request_input_serialization(self): """ - Test serialization/deserialization for MessageInput + Test serialization/deserialization for LogRequestInput """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5525,14 +5482,14 @@ def test_message_input_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5543,213 +5500,85 @@ def test_message_input_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['analytics'] = request_analytics_model - message_input_model_json['options'] = message_input_options_model + # Construct a json representation of a LogRequestInput model + log_request_input_model_json = {} + log_request_input_model_json['message_type'] = 'text' + log_request_input_model_json['text'] = 'testString' + log_request_input_model_json['intents'] = [runtime_intent_model] + log_request_input_model_json['entities'] = [runtime_entity_model] + log_request_input_model_json['suggestion_id'] = 'testString' + log_request_input_model_json['attachments'] = [message_input_attachment_model] + log_request_input_model_json['analytics'] = request_analytics_model + log_request_input_model_json['options'] = message_input_options_model + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) + assert log_request_input_model != False + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ + log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False - - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) - - # Verify the model instances are equivalent - assert message_input_model == message_input_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json - -class TestModel_MessageInputAttachment(): - """ - Test Class for MessageInputAttachment - """ - - def test_message_input_attachment_serialization(self): - """ - Test serialization/deserialization for MessageInputAttachment - """ - - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' - - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False - - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) - - # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json - -class TestModel_MessageInputOptions(): - """ - Test Class for MessageInputOptions - """ - - def test_message_input_options_serialization(self): - """ - Test serialization/deserialization for MessageInputOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) - - # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 + # Verify the model instances are equivalent + assert log_request_input_model == log_request_input_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json - -class TestModel_MessageInputOptionsSpelling(): - """ - Test Class for MessageInputOptionsSpelling - """ - - def test_message_input_options_spelling_serialization(self): - """ - Test serialization/deserialization for MessageInputOptionsSpelling - """ - - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True - - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False - - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + log_request_input_model_json2 = log_request_input_model.to_dict() + assert log_request_input_model_json2 == log_request_input_model_json - # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_MessageInputOptionsStateless(): +class TestModel_LogResponse: """ - Test Class for MessageInputOptionsStateless + Test Class for LogResponse """ - def test_message_input_options_stateless_serialization(self): + def test_log_response_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsStateless + Test serialization/deserialization for LogResponse """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a MessageInputOptionsStateless model - message_input_options_stateless_model_json = {} - message_input_options_stateless_model_json['restart'] = False - message_input_options_stateless_model_json['alternate_intents'] = False - message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model_json['debug'] = False - - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) - assert message_input_options_stateless_model != False - - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model_dict = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json).__dict__ - message_input_options_stateless_model2 = MessageInputOptionsStateless(**message_input_options_stateless_model_dict) - - # Verify the model instances are equivalent - assert message_input_options_stateless_model == message_input_options_stateless_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() - assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json - -class TestModel_MessageInputStateless(): - """ - Test Class for MessageInputStateless - """ - - def test_message_input_stateless_serialization(self): - """ - Test serialization/deserialization for MessageInputStateless - """ + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' - # Construct dict forms of any model objects needed in order to build this model. + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5777,14 +5606,14 @@ def test_message_input_stateless_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5795,81 +5624,151 @@ def test_message_input_stateless_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a LogResponse model + log_response_model_json = {} + log_response_model_json['output'] = log_response_output_model + log_response_model_json['context'] = message_context_model + log_response_model_json['user_id'] = 'testString' + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model = LogResponse.from_dict(log_response_model_json) + assert log_response_model != False - message_input_options_stateless_model = {} # MessageInputOptionsStateless - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False - - # Construct a json representation of a MessageInputStateless model - message_input_stateless_model_json = {} - message_input_stateless_model_json['message_type'] = 'text' - message_input_stateless_model_json['text'] = 'testString' - message_input_stateless_model_json['intents'] = [runtime_intent_model] - message_input_stateless_model_json['entities'] = [runtime_entity_model] - message_input_stateless_model_json['suggestion_id'] = 'testString' - message_input_stateless_model_json['attachments'] = [message_input_attachment_model] - message_input_stateless_model_json['analytics'] = request_analytics_model - message_input_stateless_model_json['options'] = message_input_options_stateless_model - - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model = MessageInputStateless.from_dict(message_input_stateless_model_json) - assert message_input_stateless_model != False - - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model_dict = MessageInputStateless.from_dict(message_input_stateless_model_json).__dict__ - message_input_stateless_model2 = MessageInputStateless(**message_input_stateless_model_dict) + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ + log_response_model2 = LogResponse(**log_response_model_dict) # Verify the model instances are equivalent - assert message_input_stateless_model == message_input_stateless_model2 + assert log_response_model == log_response_model2 # Convert model instance back to dict and verify no loss of data - message_input_stateless_model_json2 = message_input_stateless_model.to_dict() - assert message_input_stateless_model_json2 == message_input_stateless_model_json + log_response_model_json2 = log_response_model.to_dict() + assert log_response_model_json2 == log_response_model_json -class TestModel_MessageOutput(): + +class TestModel_LogResponseOutput: """ - Test Class for MessageOutput + Test Class for LogResponseOutput """ - def test_message_output_serialization(self): + def test_log_response_output_serialization(self): """ - Test serialization/deserialization for MessageOutput + Test serialization/deserialization for LogResponseOutput """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5897,14 +5796,14 @@ def test_message_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5915,35 +5814,35 @@ def test_message_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -5951,239 +5850,200 @@ def test_message_output_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - # Construct a json representation of a MessageOutput model - message_output_model_json = {} - message_output_model_json['generic'] = [runtime_response_generic_model] - message_output_model_json['intents'] = [runtime_intent_model] - message_output_model_json['entities'] = [runtime_entity_model] - message_output_model_json['actions'] = [dialog_node_action_model] - message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'foo': 'bar'} - message_output_model_json['spelling'] = message_output_spelling_model + # Construct a json representation of a LogResponseOutput model + log_response_output_model_json = {} + log_response_output_model_json['generic'] = [runtime_response_generic_model] + log_response_output_model_json['intents'] = [runtime_intent_model] + log_response_output_model_json['entities'] = [runtime_entity_model] + log_response_output_model_json['actions'] = [dialog_node_action_model] + log_response_output_model_json['debug'] = message_output_debug_model + log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model_json['spelling'] = message_output_spelling_model - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model = MessageOutput.from_dict(message_output_model_json) - assert message_output_model != False + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) + assert log_response_output_model != False - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ - message_output_model2 = MessageOutput(**message_output_model_dict) + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ + log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) # Verify the model instances are equivalent - assert message_output_model == message_output_model2 + assert log_response_output_model == log_response_output_model2 # Convert model instance back to dict and verify no loss of data - message_output_model_json2 = message_output_model.to_dict() - assert message_output_model_json2 == message_output_model_json + log_response_output_model_json2 = log_response_output_model.to_dict() + assert log_response_output_model_json2 == log_response_output_model_json + -class TestModel_MessageOutputDebug(): +class TestModel_MessageContext: """ - Test Class for MessageOutputDebug + Test Class for MessageContext """ - def test_message_output_debug_serialization(self): + def test_message_context_serialization(self): """ - Test serialization/deserialization for MessageOutputDebug + Test serialization/deserialization for MessageContext """ # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - # Construct a json representation of a MessageOutputDebug model - message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model_json['log_messages'] = [dialog_log_message_model] - message_output_debug_model_json['branch_exited'] = True - message_output_debug_model_json['branch_exited_reason'] = 'completed' - message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) - assert message_output_debug_model != False + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ - message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) # Verify the model instances are equivalent - assert message_output_debug_model == message_output_debug_model2 + assert message_context_model == message_context_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_model_json2 = message_output_debug_model.to_dict() - assert message_output_debug_model_json2 == message_output_debug_model_json + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json -class TestModel_MessageOutputSpelling(): + +class TestModel_MessageContextActionSkill: """ - Test Class for MessageOutputSpelling + Test Class for MessageContextActionSkill """ - def test_message_output_spelling_serialization(self): + def test_message_context_action_skill_serialization(self): """ - Test serialization/deserialization for MessageOutputSpelling + Test serialization/deserialization for MessageContextActionSkill """ - # Construct a json representation of a MessageOutputSpelling model - message_output_spelling_model_json = {} - message_output_spelling_model_json['text'] = 'testString' - message_output_spelling_model_json['original_text'] = 'testString' - message_output_spelling_model_json['suggested_text'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) - assert message_output_spelling_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ - message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + # Construct a json representation of a MessageContextActionSkill model + message_context_action_skill_model_json = {} + message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['system'] = message_context_skill_system_model + message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) + assert message_context_action_skill_model != False + + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ + message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) # Verify the model instances are equivalent - assert message_output_spelling_model == message_output_spelling_model2 + assert message_context_action_skill_model == message_context_action_skill_model2 # Convert model instance back to dict and verify no loss of data - message_output_spelling_model_json2 = message_output_spelling_model.to_dict() - assert message_output_spelling_model_json2 == message_output_spelling_model_json + message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() + assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + -class TestModel_MessageRequest(): +class TestModel_MessageContextDialogSkill: """ - Test Class for MessageRequest + Test Class for MessageContextDialogSkill """ - def test_message_request_serialization(self): + def test_message_context_dialog_skill_serialization(self): """ - Test serialization/deserialization for MessageRequest + Test serialization/deserialization for MessageContextDialogSkill """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a json representation of a MessageContextDialogSkill model + message_context_dialog_skill_model_json = {} + message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model_json['system'] = message_context_skill_system_model - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) + assert message_context_dialog_skill_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ + message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert message_context_dialog_skill_model == message_context_dialog_skill_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() + assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageContextGlobal: + """ + Test Class for MessageContextGlobal + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + def test_message_context_global_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobal + """ - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'Hello' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -6191,83 +6051,173 @@ def test_message_request_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False + + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + # Verify the model instances are equivalent + assert message_context_global_model == message_context_global_model2 - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + # Convert model instance back to dict and verify no loss of data + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} +class TestModel_MessageContextGlobalSystem: + """ + Test Class for MessageContextGlobalSystem + """ + + def test_message_context_global_system_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobalSystem + """ + + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True + + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False + + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) + + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json - # Construct a json representation of a MessageRequest model - message_request_model_json = {} - message_request_model_json['input'] = message_input_model - message_request_model_json['context'] = message_context_model - message_request_model_json['user_id'] = 'testString' - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model = MessageRequest.from_dict(message_request_model_json) - assert message_request_model != False +class TestModel_MessageContextSkillSystem: + """ + Test Class for MessageContextSkillSystem + """ + + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ + + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ - message_request_model2 = MessageRequest(**message_request_model_dict) + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) # Verify the model instances are equivalent - assert message_request_model == message_request_model2 + assert message_context_skill_system_model == message_context_skill_system_model2 # Convert model instance back to dict and verify no loss of data - message_request_model_json2 = message_request_model.to_dict() - assert message_request_model_json2 == message_request_model_json + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == expected_dict + -class TestModel_MessageResponse(): +class TestModel_MessageContextSkills: """ - Test Class for MessageResponse + Test Class for MessageContextSkills """ - def test_message_response_serialization(self): + def test_message_context_skills_serialization(self): """ - Test serialization/deserialization for MessageResponse + Test serialization/deserialization for MessageContextSkills """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + message_context_skills_model_json['actions skill'] = message_context_action_skill_model + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + + # Verify the model instances are equivalent + assert message_context_skills_model == message_context_skills_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json + + +class TestModel_MessageInput: + """ + Test Class for MessageInput + """ + + def test_message_input_serialization(self): + """ + Test serialization/deserialization for MessageInput + """ - runtime_intent_model = {} # RuntimeIntent + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6295,14 +6245,14 @@ def test_message_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -6313,150 +6263,189 @@ def test_message_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} - message_output_model['spelling'] = message_output_spelling_model + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model +class TestModel_MessageInputAttachment: + """ + Test Class for MessageInputAttachment + """ - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + # Verify the model instances are equivalent + assert message_input_attachment_model == message_input_attachment_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json + + +class TestModel_MessageInputOptions: + """ + Test Class for MessageInputOptions + """ + + def test_message_input_options_serialization(self): + """ + Test serialization/deserialization for MessageInputOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['async_callout'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json + + +class TestModel_MessageInputOptionsSpelling: + """ + Test Class for MessageInputOptionsSpelling + """ + + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ - # Construct a json representation of a MessageResponse model - message_response_model_json = {} - message_response_model_json['output'] = message_output_model - message_response_model_json['context'] = message_context_model - message_response_model_json['user_id'] = 'testString' + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model = MessageResponse.from_dict(message_response_model_json) - assert message_response_model != False + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ - message_response_model2 = MessageResponse(**message_response_model_dict) + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert message_response_model == message_response_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - message_response_model_json2 = message_response_model.to_dict() - assert message_response_model_json2 == message_response_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + -class TestModel_MessageResponseStateless(): +class TestModel_MessageOutput: """ - Test Class for MessageResponseStateless + Test Class for MessageOutput """ - def test_message_response_stateless_serialization(self): + def test_message_output_serialization(self): """ - Test serialization/deserialization for MessageResponseStateless + Test serialization/deserialization for MessageOutput """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6484,14 +6473,14 @@ def test_message_response_stateless_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -6502,35 +6491,35 @@ def test_message_response_stateless_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -6538,91 +6527,147 @@ def test_message_response_stateless_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} - message_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_output_model_json['spelling'] = message_output_spelling_model - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert message_output_model == message_output_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json + + +class TestModel_MessageOutputDebug: + """ + Test Class for MessageOutputDebug + """ - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + def test_message_output_debug_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebug + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - message_context_stateless_model = {} # MessageContextStateless - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'foo': 'bar'} + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct a json representation of a MessageResponseStateless model - message_response_stateless_model_json = {} - message_response_stateless_model_json['output'] = message_output_model - message_response_stateless_model_json['context'] = message_context_stateless_model - message_response_stateless_model_json['user_id'] = 'testString' + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) - assert message_response_stateless_model != False + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ - message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) # Verify the model instances are equivalent - assert message_response_stateless_model == message_response_stateless_model2 + assert message_output_debug_model == message_output_debug_model2 # Convert model instance back to dict and verify no loss of data - message_response_stateless_model_json2 = message_response_stateless_model.to_dict() - assert message_response_stateless_model_json2 == message_response_stateless_model_json + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json + -class TestModel_Pagination(): +class TestModel_MessageOutputSpelling: """ - Test Class for Pagination + Test Class for MessageOutputSpelling """ - def test_pagination_serialization(self): + def test_message_output_spelling_serialization(self): + """ + Test serialization/deserialization for MessageOutputSpelling + """ + + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' + + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False + + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + + # Verify the model instances are equivalent + assert message_output_spelling_model == message_output_spelling_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json + + +class TestModel_Pagination: + """ + Test Class for Pagination + """ + + def test_pagination_serialization(self): """ Test serialization/deserialization for Pagination """ @@ -6651,7 +6696,8 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestModel_Release(): + +class TestModel_Release: """ Test Class for Release """ @@ -6680,7 +6726,8 @@ def test_release_serialization(self): release_model_json2 = release_model.to_dict() assert release_model_json2 == release_model_json -class TestModel_ReleaseCollection(): + +class TestModel_ReleaseCollection: """ Test Class for ReleaseCollection """ @@ -6692,10 +6739,10 @@ def test_release_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - release_model = {} # Release + release_model = {} # Release release_model['description'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -6723,7 +6770,8 @@ def test_release_collection_serialization(self): release_collection_model_json2 = release_collection_model.to_dict() assert release_collection_model_json2 == release_collection_model_json -class TestModel_ReleaseContent(): + +class TestModel_ReleaseContent: """ Test Class for ReleaseContent """ @@ -6751,7 +6799,8 @@ def test_release_content_serialization(self): release_content_model_json2 = release_content_model.to_dict() assert release_content_model_json2 == release_content_model_json -class TestModel_ReleaseSkill(): + +class TestModel_ReleaseSkill: """ Test Class for ReleaseSkill """ @@ -6782,7 +6831,8 @@ def test_release_skill_serialization(self): release_skill_model_json2 = release_skill_model.to_dict() assert release_skill_model_json2 == release_skill_model_json -class TestModel_RequestAnalytics(): + +class TestModel_RequestAnalytics: """ Test Class for RequestAnalytics """ @@ -6813,7 +6863,8 @@ def test_request_analytics_serialization(self): request_analytics_model_json2 = request_analytics_model.to_dict() assert request_analytics_model_json2 == request_analytics_model_json -class TestModel_ResponseGenericChannel(): + +class TestModel_ResponseGenericChannel: """ Test Class for ResponseGenericChannel """ @@ -6842,7 +6893,8 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_RuntimeEntity(): + +class TestModel_RuntimeEntity: """ Test Class for RuntimeEntity """ @@ -6854,11 +6906,11 @@ def test_runtime_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6886,11 +6938,11 @@ def test_runtime_entity_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' # Construct a json representation of a RuntimeEntity model @@ -6920,7 +6972,8 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_RuntimeEntityAlternative(): + +class TestModel_RuntimeEntityAlternative: """ Test Class for RuntimeEntityAlternative """ @@ -6950,7 +7003,8 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_RuntimeEntityInterpretation(): + +class TestModel_RuntimeEntityInterpretation: """ Test Class for RuntimeEntityInterpretation """ @@ -7004,7 +7058,8 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_RuntimeEntityRole(): + +class TestModel_RuntimeEntityRole: """ Test Class for RuntimeEntityRole """ @@ -7033,7 +7088,8 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_RuntimeIntent(): + +class TestModel_RuntimeIntent: """ Test Class for RuntimeIntent """ @@ -7064,7 +7120,8 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_SearchResult(): + +class TestModel_SearchResult: """ Test Class for SearchResult """ @@ -7076,17 +7133,17 @@ def test_search_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model = {} # SearchResultMetadata search_result_metadata_model['confidence'] = 72.5 search_result_metadata_model['score'] = 72.5 - search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model = {} # SearchResultHighlight search_result_highlight_model['body'] = ['testString'] search_result_highlight_model['title'] = ['testString'] search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] - search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model = {} # SearchResultAnswer search_result_answer_model['text'] = 'testString' search_result_answer_model['confidence'] = 0 @@ -7115,7 +7172,8 @@ def test_search_result_serialization(self): search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json -class TestModel_SearchResultAnswer(): + +class TestModel_SearchResultAnswer: """ Test Class for SearchResultAnswer """ @@ -7145,7 +7203,8 @@ def test_search_result_answer_serialization(self): search_result_answer_model_json2 = search_result_answer_model.to_dict() assert search_result_answer_model_json2 == search_result_answer_model_json -class TestModel_SearchResultHighlight(): + +class TestModel_SearchResultHighlight: """ Test Class for SearchResultHighlight """ @@ -7187,7 +7246,8 @@ def test_search_result_highlight_serialization(self): actual_dict = search_result_highlight_model.get_properties() assert actual_dict == expected_dict -class TestModel_SearchResultMetadata(): + +class TestModel_SearchResultMetadata: """ Test Class for SearchResultMetadata """ @@ -7217,7 +7277,8 @@ def test_search_result_metadata_serialization(self): search_result_metadata_model_json2 = search_result_metadata_model.to_dict() assert search_result_metadata_model_json2 == search_result_metadata_model_json -class TestModel_SearchSettings(): + +class TestModel_SearchSettings: """ Test Class for SearchSettings """ @@ -7229,11 +7290,11 @@ def test_search_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model = {} # SearchSettingsDiscovery search_settings_discovery_model['instance_id'] = 'testString' search_settings_discovery_model['project_id'] = 'testString' search_settings_discovery_model['url'] = 'testString' @@ -7244,12 +7305,12 @@ def test_search_settings_serialization(self): search_settings_discovery_model['find_answers'] = True search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model = {} # SearchSettingsMessages search_settings_messages_model['success'] = 'testString' search_settings_messages_model['error'] = 'testString' search_settings_messages_model['no_result'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' @@ -7275,7 +7336,8 @@ def test_search_settings_serialization(self): search_settings_model_json2 = search_settings_model.to_dict() assert search_settings_model_json2 == search_settings_model_json -class TestModel_SearchSettingsDiscovery(): + +class TestModel_SearchSettingsDiscovery: """ Test Class for SearchSettingsDiscovery """ @@ -7287,7 +7349,7 @@ def test_search_settings_discovery_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' @@ -7303,411 +7365,1227 @@ def test_search_settings_discovery_serialization(self): search_settings_discovery_model_json['find_answers'] = True search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) - assert search_settings_discovery_model != False + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) + assert search_settings_discovery_model != False + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ + search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_model == search_settings_discovery_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() + assert search_settings_discovery_model_json2 == search_settings_discovery_model_json + + +class TestModel_SearchSettingsDiscoveryAuthentication: + """ + Test Class for SearchSettingsDiscoveryAuthentication + """ + + def test_search_settings_discovery_authentication_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + """ + + # Construct a json representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model_json = {} + search_settings_discovery_authentication_model_json['basic'] = 'testString' + search_settings_discovery_authentication_model_json['bearer'] = 'testString' + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) + assert search_settings_discovery_authentication_model != False + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ + search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() + assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json + + +class TestModel_SearchSettingsMessages: + """ + Test Class for SearchSettingsMessages + """ + + def test_search_settings_messages_serialization(self): + """ + Test serialization/deserialization for SearchSettingsMessages + """ + + # Construct a json representation of a SearchSettingsMessages model + search_settings_messages_model_json = {} + search_settings_messages_model_json['success'] = 'testString' + search_settings_messages_model_json['error'] = 'testString' + search_settings_messages_model_json['no_result'] = 'testString' + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) + assert search_settings_messages_model != False + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ + search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) + + # Verify the model instances are equivalent + assert search_settings_messages_model == search_settings_messages_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_messages_model_json2 = search_settings_messages_model.to_dict() + assert search_settings_messages_model_json2 == search_settings_messages_model_json + + +class TestModel_SearchSettingsSchemaMapping: + """ + Test Class for SearchSettingsSchemaMapping + """ + + def test_search_settings_schema_mapping_serialization(self): + """ + Test serialization/deserialization for SearchSettingsSchemaMapping + """ + + # Construct a json representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model_json = {} + search_settings_schema_mapping_model_json['url'] = 'testString' + search_settings_schema_mapping_model_json['body'] = 'testString' + search_settings_schema_mapping_model_json['title'] = 'testString' + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) + assert search_settings_schema_mapping_model != False + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ + search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) + + # Verify the model instances are equivalent + assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() + assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json + + +class TestModel_SearchSkillWarning: + """ + Test Class for SearchSkillWarning + """ + + def test_search_skill_warning_serialization(self): + """ + Test serialization/deserialization for SearchSkillWarning + """ + + # Construct a json representation of a SearchSkillWarning model + search_skill_warning_model_json = {} + search_skill_warning_model_json['code'] = 'testString' + search_skill_warning_model_json['path'] = 'testString' + search_skill_warning_model_json['message'] = 'testString' + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) + assert search_skill_warning_model != False + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ + search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) + + # Verify the model instances are equivalent + assert search_skill_warning_model == search_skill_warning_model2 + + # Convert model instance back to dict and verify no loss of data + search_skill_warning_model_json2 = search_skill_warning_model.to_dict() + assert search_skill_warning_model_json2 == search_skill_warning_model_json + + +class TestModel_SessionResponse: + """ + Test Class for SessionResponse + """ + + def test_session_response_serialization(self): + """ + Test serialization/deserialization for SessionResponse + """ + + # Construct a json representation of a SessionResponse model + session_response_model_json = {} + session_response_model_json['session_id'] = 'testString' + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model = SessionResponse.from_dict(session_response_model_json) + assert session_response_model != False + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ + session_response_model2 = SessionResponse(**session_response_model_dict) + + # Verify the model instances are equivalent + assert session_response_model == session_response_model2 + + # Convert model instance back to dict and verify no loss of data + session_response_model_json2 = session_response_model.to_dict() + assert session_response_model_json2 == session_response_model_json + + +class TestModel_Skill: + """ + Test Class for Skill + """ + + def test_skill_serialization(self): + """ + Test serialization/deserialization for Skill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a json representation of a Skill model + skill_model_json = {} + skill_model_json['name'] = 'testString' + skill_model_json['description'] = 'testString' + skill_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_model_json['dialog_settings'] = {'anyKey': 'anyValue'} + skill_model_json['search_settings'] = search_settings_model + skill_model_json['language'] = 'testString' + skill_model_json['type'] = 'action' + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model = Skill.from_dict(skill_model_json) + assert skill_model != False + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model_dict = Skill.from_dict(skill_model_json).__dict__ + skill_model2 = Skill(**skill_model_dict) + + # Verify the model instances are equivalent + assert skill_model == skill_model2 + + # Convert model instance back to dict and verify no loss of data + skill_model_json2 = skill_model.to_dict() + assert skill_model_json2 == skill_model_json + + +class TestModel_SkillImport: + """ + Test Class for SkillImport + """ + + def test_skill_import_serialization(self): + """ + Test serialization/deserialization for SkillImport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a json representation of a SkillImport model + skill_import_model_json = {} + skill_import_model_json['name'] = 'testString' + skill_import_model_json['description'] = 'testString' + skill_import_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_import_model_json['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model_json['search_settings'] = search_settings_model + skill_import_model_json['language'] = 'testString' + skill_import_model_json['type'] = 'action' + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model = SkillImport.from_dict(skill_import_model_json) + assert skill_import_model != False + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ + skill_import_model2 = SkillImport(**skill_import_model_dict) + + # Verify the model instances are equivalent + assert skill_import_model == skill_import_model2 + + # Convert model instance back to dict and verify no loss of data + skill_import_model_json2 = skill_import_model.to_dict() + assert skill_import_model_json2 == skill_import_model_json + + +class TestModel_SkillsAsyncRequestStatus: + """ + Test Class for SkillsAsyncRequestStatus + """ + + def test_skills_async_request_status_serialization(self): + """ + Test serialization/deserialization for SkillsAsyncRequestStatus + """ + + # Construct a json representation of a SkillsAsyncRequestStatus model + skills_async_request_status_model_json = {} + + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) + assert skills_async_request_status_model != False + + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ + skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) + + # Verify the model instances are equivalent + assert skills_async_request_status_model == skills_async_request_status_model2 + + # Convert model instance back to dict and verify no loss of data + skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() + assert skills_async_request_status_model_json2 == skills_async_request_status_model_json + + +class TestModel_SkillsExport: + """ + Test Class for SkillsExport + """ + + def test_skills_export_serialization(self): + """ + Test serialization/deserialization for SkillsExport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + skill_model = {} # Skill + skill_model['name'] = 'testString' + skill_model['description'] = 'testString' + skill_model['workspace'] = {'anyKey': 'anyValue'} + skill_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_model['search_settings'] = search_settings_model + skill_model['language'] = 'testString' + skill_model['type'] = 'action' + + assistant_state_model = {} # AssistantState + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Construct a json representation of a SkillsExport model + skills_export_model_json = {} + skills_export_model_json['assistant_skills'] = [skill_model] + skills_export_model_json['assistant_state'] = assistant_state_model + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model = SkillsExport.from_dict(skills_export_model_json) + assert skills_export_model != False + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ + skills_export_model2 = SkillsExport(**skills_export_model_dict) + + # Verify the model instances are equivalent + assert skills_export_model == skills_export_model2 + + # Convert model instance back to dict and verify no loss of data + skills_export_model_json2 = skills_export_model.to_dict() + assert skills_export_model_json2 == skills_export_model_json + + +class TestModel_StatefulMessageResponse: + """ + Test Class for StatefulMessageResponse + """ + + def test_stateful_message_response_serialization(self): + """ + Test serialization/deserialization for StatefulMessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a StatefulMessageResponse model + stateful_message_response_model_json = {} + stateful_message_response_model_json['output'] = message_output_model + stateful_message_response_model_json['context'] = message_context_model + stateful_message_response_model_json['user_id'] = 'testString' + stateful_message_response_model_json['masked_output'] = message_output_model + stateful_message_response_model_json['masked_input'] = message_input_model - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ - search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model = StatefulMessageResponse.from_dict(stateful_message_response_model_json) + assert stateful_message_response_model != False + + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model_dict = StatefulMessageResponse.from_dict(stateful_message_response_model_json).__dict__ + stateful_message_response_model2 = StatefulMessageResponse(**stateful_message_response_model_dict) # Verify the model instances are equivalent - assert search_settings_discovery_model == search_settings_discovery_model2 + assert stateful_message_response_model == stateful_message_response_model2 # Convert model instance back to dict and verify no loss of data - search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() - assert search_settings_discovery_model_json2 == search_settings_discovery_model_json + stateful_message_response_model_json2 = stateful_message_response_model.to_dict() + assert stateful_message_response_model_json2 == stateful_message_response_model_json + -class TestModel_SearchSettingsDiscoveryAuthentication(): +class TestModel_StatelessMessageContext: """ - Test Class for SearchSettingsDiscoveryAuthentication + Test Class for StatelessMessageContext """ - def test_search_settings_discovery_authentication_serialization(self): + def test_stateless_message_context_serialization(self): """ - Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + Test serialization/deserialization for StatelessMessageContext """ - # Construct a json representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model_json = {} - search_settings_discovery_authentication_model_json['basic'] = 'testString' - search_settings_discovery_authentication_model_json['bearer'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) - assert search_settings_discovery_authentication_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ - search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' - # Verify the model instances are equivalent - assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Convert model instance back to dict and verify no loss of data - search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() - assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model -class TestModel_SearchSettingsMessages(): - """ - Test Class for SearchSettingsMessages - """ + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} - def test_search_settings_messages_serialization(self): - """ - Test serialization/deserialization for SearchSettingsMessages - """ + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model - # Construct a json representation of a SearchSettingsMessages model - search_settings_messages_model_json = {} - search_settings_messages_model_json['success'] = 'testString' - search_settings_messages_model_json['error'] = 'testString' - search_settings_messages_model_json['no_result'] = 'testString' + # Construct a json representation of a StatelessMessageContext model + stateless_message_context_model_json = {} + stateless_message_context_model_json['global'] = stateless_message_context_global_model + stateless_message_context_model_json['skills'] = stateless_message_context_skills_model + stateless_message_context_model_json['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) - assert search_settings_messages_model != False + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model = StatelessMessageContext.from_dict(stateless_message_context_model_json) + assert stateless_message_context_model != False - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ - search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model_dict = StatelessMessageContext.from_dict(stateless_message_context_model_json).__dict__ + stateless_message_context_model2 = StatelessMessageContext(**stateless_message_context_model_dict) # Verify the model instances are equivalent - assert search_settings_messages_model == search_settings_messages_model2 + assert stateless_message_context_model == stateless_message_context_model2 # Convert model instance back to dict and verify no loss of data - search_settings_messages_model_json2 = search_settings_messages_model.to_dict() - assert search_settings_messages_model_json2 == search_settings_messages_model_json + stateless_message_context_model_json2 = stateless_message_context_model.to_dict() + assert stateless_message_context_model_json2 == stateless_message_context_model_json -class TestModel_SearchSettingsSchemaMapping(): + +class TestModel_StatelessMessageContextGlobal: """ - Test Class for SearchSettingsSchemaMapping + Test Class for StatelessMessageContextGlobal """ - def test_search_settings_schema_mapping_serialization(self): + def test_stateless_message_context_global_serialization(self): """ - Test serialization/deserialization for SearchSettingsSchemaMapping + Test serialization/deserialization for StatelessMessageContextGlobal """ - # Construct a json representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model_json = {} - search_settings_schema_mapping_model_json['url'] = 'testString' - search_settings_schema_mapping_model_json['body'] = 'testString' - search_settings_schema_mapping_model_json['title'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) - assert search_settings_schema_mapping_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ - search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) + # Construct a json representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model_json = {} + stateless_message_context_global_model_json['system'] = message_context_global_system_model + stateless_message_context_global_model_json['session_id'] = 'testString' + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json) + assert stateless_message_context_global_model != False + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model_dict = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json).__dict__ + stateless_message_context_global_model2 = StatelessMessageContextGlobal(**stateless_message_context_global_model_dict) # Verify the model instances are equivalent - assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 + assert stateless_message_context_global_model == stateless_message_context_global_model2 # Convert model instance back to dict and verify no loss of data - search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() - assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json + stateless_message_context_global_model_json2 = stateless_message_context_global_model.to_dict() + assert stateless_message_context_global_model_json2 == stateless_message_context_global_model_json + -class TestModel_SearchSkillWarning(): +class TestModel_StatelessMessageContextSkills: """ - Test Class for SearchSkillWarning + Test Class for StatelessMessageContextSkills """ - def test_search_skill_warning_serialization(self): + def test_stateless_message_context_skills_serialization(self): """ - Test serialization/deserialization for SearchSkillWarning + Test serialization/deserialization for StatelessMessageContextSkills """ - # Construct a json representation of a SearchSkillWarning model - search_skill_warning_model_json = {} - search_skill_warning_model_json['code'] = 'testString' - search_skill_warning_model_json['path'] = 'testString' - search_skill_warning_model_json['message'] = 'testString' - - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) - assert search_skill_warning_model != False - - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ - search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) - - # Verify the model instances are equivalent - assert search_skill_warning_model == search_skill_warning_model2 + # Construct dict forms of any model objects needed in order to build this model. - # Convert model instance back to dict and verify no loss of data - search_skill_warning_model_json2 = search_skill_warning_model.to_dict() - assert search_skill_warning_model_json2 == search_skill_warning_model_json + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' -class TestModel_SessionResponse(): - """ - Test Class for SessionResponse - """ + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - def test_session_response_serialization(self): - """ - Test serialization/deserialization for SessionResponse - """ + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} - # Construct a json representation of a SessionResponse model - session_response_model_json = {} - session_response_model_json['session_id'] = 'testString' + # Construct a json representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model_json = {} + stateless_message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model_json['actions skill'] = stateless_message_context_skills_actions_skill_model - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model = SessionResponse.from_dict(session_response_model_json) - assert session_response_model != False + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json) + assert stateless_message_context_skills_model != False - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ - session_response_model2 = SessionResponse(**session_response_model_dict) + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model_dict = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json).__dict__ + stateless_message_context_skills_model2 = StatelessMessageContextSkills(**stateless_message_context_skills_model_dict) # Verify the model instances are equivalent - assert session_response_model == session_response_model2 + assert stateless_message_context_skills_model == stateless_message_context_skills_model2 # Convert model instance back to dict and verify no loss of data - session_response_model_json2 = session_response_model.to_dict() - assert session_response_model_json2 == session_response_model_json + stateless_message_context_skills_model_json2 = stateless_message_context_skills_model.to_dict() + assert stateless_message_context_skills_model_json2 == stateless_message_context_skills_model_json -class TestModel_Skill(): + +class TestModel_StatelessMessageContextSkillsActionsSkill: """ - Test Class for Skill + Test Class for StatelessMessageContextSkillsActionsSkill """ - def test_skill_serialization(self): + def test_stateless_message_context_skills_actions_skill_serialization(self): """ - Test serialization/deserialization for Skill + Test serialization/deserialization for StatelessMessageContextSkillsActionsSkill """ # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a json representation of a Skill model - skill_model_json = {} - skill_model_json['name'] = 'testString' - skill_model_json['description'] = 'testString' - skill_model_json['workspace'] = {'foo': 'bar'} - skill_model_json['dialog_settings'] = {'foo': 'bar'} - skill_model_json['search_settings'] = search_settings_model - skill_model_json['language'] = 'testString' - skill_model_json['type'] = 'action' + # Construct a json representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model_json = {} + stateless_message_context_skills_actions_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_skill_variables'] = {'anyKey': 'anyValue'} - # Construct a model instance of Skill by calling from_dict on the json representation - skill_model = Skill.from_dict(skill_model_json) - assert skill_model != False + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json) + assert stateless_message_context_skills_actions_skill_model != False - # Construct a model instance of Skill by calling from_dict on the json representation - skill_model_dict = Skill.from_dict(skill_model_json).__dict__ - skill_model2 = Skill(**skill_model_dict) + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model_dict = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json).__dict__ + stateless_message_context_skills_actions_skill_model2 = StatelessMessageContextSkillsActionsSkill(**stateless_message_context_skills_actions_skill_model_dict) # Verify the model instances are equivalent - assert skill_model == skill_model2 + assert stateless_message_context_skills_actions_skill_model == stateless_message_context_skills_actions_skill_model2 # Convert model instance back to dict and verify no loss of data - skill_model_json2 = skill_model.to_dict() - assert skill_model_json2 == skill_model_json + stateless_message_context_skills_actions_skill_model_json2 = stateless_message_context_skills_actions_skill_model.to_dict() + assert stateless_message_context_skills_actions_skill_model_json2 == stateless_message_context_skills_actions_skill_model_json -class TestModel_SkillImport(): + +class TestModel_StatelessMessageInput: """ - Test Class for SkillImport + Test Class for StatelessMessageInput """ - def test_skill_import_serialization(self): + def test_stateless_message_input_serialization(self): """ - Test serialization/deserialization for SkillImport + Test serialization/deserialization for StatelessMessageInput """ # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Construct a json representation of a SkillImport model - skill_import_model_json = {} - skill_import_model_json['name'] = 'testString' - skill_import_model_json['description'] = 'testString' - skill_import_model_json['workspace'] = {'foo': 'bar'} - skill_import_model_json['dialog_settings'] = {'foo': 'bar'} - skill_import_model_json['search_settings'] = search_settings_model - skill_import_model_json['language'] = 'testString' - skill_import_model_json['type'] = 'action' + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a model instance of SkillImport by calling from_dict on the json representation - skill_import_model = SkillImport.from_dict(skill_import_model_json) - assert skill_import_model != False + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Construct a model instance of SkillImport by calling from_dict on the json representation - skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ - skill_import_model2 = SkillImport(**skill_import_model_dict) + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + stateless_message_input_options_model = {} # StatelessMessageInputOptions + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a json representation of a StatelessMessageInput model + stateless_message_input_model_json = {} + stateless_message_input_model_json['message_type'] = 'text' + stateless_message_input_model_json['text'] = 'testString' + stateless_message_input_model_json['intents'] = [runtime_intent_model] + stateless_message_input_model_json['entities'] = [runtime_entity_model] + stateless_message_input_model_json['suggestion_id'] = 'testString' + stateless_message_input_model_json['attachments'] = [message_input_attachment_model] + stateless_message_input_model_json['analytics'] = request_analytics_model + stateless_message_input_model_json['options'] = stateless_message_input_options_model + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model = StatelessMessageInput.from_dict(stateless_message_input_model_json) + assert stateless_message_input_model != False + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model_dict = StatelessMessageInput.from_dict(stateless_message_input_model_json).__dict__ + stateless_message_input_model2 = StatelessMessageInput(**stateless_message_input_model_dict) # Verify the model instances are equivalent - assert skill_import_model == skill_import_model2 + assert stateless_message_input_model == stateless_message_input_model2 # Convert model instance back to dict and verify no loss of data - skill_import_model_json2 = skill_import_model.to_dict() - assert skill_import_model_json2 == skill_import_model_json + stateless_message_input_model_json2 = stateless_message_input_model.to_dict() + assert stateless_message_input_model_json2 == stateless_message_input_model_json -class TestModel_SkillsAsyncRequestStatus(): + +class TestModel_StatelessMessageInputOptions: """ - Test Class for SkillsAsyncRequestStatus + Test Class for StatelessMessageInputOptions """ - def test_skills_async_request_status_serialization(self): + def test_stateless_message_input_options_serialization(self): """ - Test serialization/deserialization for SkillsAsyncRequestStatus + Test serialization/deserialization for StatelessMessageInputOptions """ - # Construct a json representation of a SkillsAsyncRequestStatus model - skills_async_request_status_model_json = {} + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation - skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) - assert skills_async_request_status_model != False + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation - skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ - skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) + # Construct a json representation of a StatelessMessageInputOptions model + stateless_message_input_options_model_json = {} + stateless_message_input_options_model_json['restart'] = False + stateless_message_input_options_model_json['alternate_intents'] = False + stateless_message_input_options_model_json['async_callout'] = False + stateless_message_input_options_model_json['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model_json['debug'] = False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json) + assert stateless_message_input_options_model != False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model_dict = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json).__dict__ + stateless_message_input_options_model2 = StatelessMessageInputOptions(**stateless_message_input_options_model_dict) # Verify the model instances are equivalent - assert skills_async_request_status_model == skills_async_request_status_model2 + assert stateless_message_input_options_model == stateless_message_input_options_model2 # Convert model instance back to dict and verify no loss of data - skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() - assert skills_async_request_status_model_json2 == skills_async_request_status_model_json + stateless_message_input_options_model_json2 = stateless_message_input_options_model.to_dict() + assert stateless_message_input_options_model_json2 == stateless_message_input_options_model_json -class TestModel_SkillsExport(): + +class TestModel_StatelessMessageResponse: """ - Test Class for SkillsExport + Test Class for StatelessMessageResponse """ - def test_skills_export_serialization(self): + def test_stateless_message_response_serialization(self): """ - Test serialization/deserialization for SkillsExport + Test serialization/deserialization for StatelessMessageResponse """ # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - skill_model = {} # Skill - skill_model['name'] = 'testString' - skill_model['description'] = 'testString' - skill_model['workspace'] = {'foo': 'bar'} - skill_model['dialog_settings'] = {'foo': 'bar'} - skill_model['search_settings'] = search_settings_model - skill_model['language'] = 'testString' - skill_model['type'] = 'action' + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - assistant_state_model = {} # AssistantState - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - # Construct a json representation of a SkillsExport model - skills_export_model_json = {} - skills_export_model_json['assistant_skills'] = [skill_model] - skills_export_model_json['assistant_state'] = assistant_state_model + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Construct a model instance of SkillsExport by calling from_dict on the json representation - skills_export_model = SkillsExport.from_dict(skills_export_model_json) - assert skills_export_model != False + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - # Construct a model instance of SkillsExport by calling from_dict on the json representation - skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ - skills_export_model2 = SkillsExport(**skills_export_model_dict) + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a StatelessMessageResponse model + stateless_message_response_model_json = {} + stateless_message_response_model_json['output'] = message_output_model + stateless_message_response_model_json['context'] = stateless_message_context_model + stateless_message_response_model_json['masked_output'] = message_output_model + stateless_message_response_model_json['masked_input'] = message_input_model + stateless_message_response_model_json['user_id'] = 'testString' + + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model = StatelessMessageResponse.from_dict(stateless_message_response_model_json) + assert stateless_message_response_model != False + + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model_dict = StatelessMessageResponse.from_dict(stateless_message_response_model_json).__dict__ + stateless_message_response_model2 = StatelessMessageResponse(**stateless_message_response_model_dict) # Verify the model instances are equivalent - assert skills_export_model == skills_export_model2 + assert stateless_message_response_model == stateless_message_response_model2 # Convert model instance back to dict and verify no loss of data - skills_export_model_json2 = skills_export_model.to_dict() - assert skills_export_model_json2 == skills_export_model_json + stateless_message_response_model_json2 = stateless_message_response_model.to_dict() + assert stateless_message_response_model_json2 == stateless_message_response_model_json + -class TestModel_StatusError(): +class TestModel_StatusError: """ Test Class for StatusError """ @@ -7736,7 +8614,8 @@ def test_status_error_serialization(self): status_error_model_json2 = status_error_model.to_dict() assert status_error_model_json2 == status_error_model_json -class TestModel_TurnEventActionSource(): + +class TestModel_TurnEventActionSource: """ Test Class for TurnEventActionSource """ @@ -7768,7 +8647,8 @@ def test_turn_event_action_source_serialization(self): turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() assert turn_event_action_source_model_json2 == turn_event_action_source_model_json -class TestModel_TurnEventCalloutCallout(): + +class TestModel_TurnEventCalloutCallout: """ Test Class for TurnEventCalloutCallout """ @@ -7781,7 +8661,7 @@ def test_turn_event_callout_callout_serialization(self): # Construct a json representation of a TurnEventCalloutCallout model turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' - turn_event_callout_callout_model_json['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model_json['result_variable'] = 'testString' # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation @@ -7799,7 +8679,8 @@ def test_turn_event_callout_callout_serialization(self): turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json -class TestModel_TurnEventCalloutError(): + +class TestModel_TurnEventCalloutError: """ Test Class for TurnEventCalloutError """ @@ -7828,7 +8709,8 @@ def test_turn_event_callout_error_serialization(self): turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json -class TestModel_TurnEventNodeSource(): + +class TestModel_TurnEventNodeSource: """ Test Class for TurnEventNodeSource """ @@ -7860,7 +8742,8 @@ def test_turn_event_node_source_serialization(self): turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() assert turn_event_node_source_model_json2 == turn_event_node_source_model_json -class TestModel_TurnEventSearchError(): + +class TestModel_TurnEventSearchError: """ Test Class for TurnEventSearchError """ @@ -7889,7 +8772,8 @@ def test_turn_event_search_error_serialization(self): turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() assert turn_event_search_error_model_json2 == turn_event_search_error_model_json -class TestModel_LogMessageSourceAction(): + +class TestModel_LogMessageSourceAction: """ Test Class for LogMessageSourceAction """ @@ -7919,7 +8803,8 @@ def test_log_message_source_action_serialization(self): log_message_source_action_model_json2 = log_message_source_action_model.to_dict() assert log_message_source_action_model_json2 == log_message_source_action_model_json -class TestModel_LogMessageSourceDialogNode(): + +class TestModel_LogMessageSourceDialogNode: """ Test Class for LogMessageSourceDialogNode """ @@ -7949,7 +8834,8 @@ def test_log_message_source_dialog_node_serialization(self): log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json -class TestModel_LogMessageSourceHandler(): + +class TestModel_LogMessageSourceHandler: """ Test Class for LogMessageSourceHandler """ @@ -7981,7 +8867,8 @@ def test_log_message_source_handler_serialization(self): log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() assert log_message_source_handler_model_json2 == log_message_source_handler_model_json -class TestModel_LogMessageSourceStep(): + +class TestModel_LogMessageSourceStep: """ Test Class for LogMessageSourceStep """ @@ -8012,7 +8899,8 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished(): + +class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished: """ Test Class for MessageOutputDebugTurnEventTurnEventActionFinished """ @@ -8024,7 +8912,7 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8037,7 +8925,7 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' - message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'foo': 'bar'} + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'anyKey': 'anyValue'} # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) @@ -8054,7 +8942,8 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventActionVisited """ @@ -8066,7 +8955,7 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8096,7 +8985,8 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventCallout(): + +class TestModel_MessageOutputDebugTurnEventTurnEventCallout: """ Test Class for MessageOutputDebugTurnEventTurnEventCallout """ @@ -8108,18 +8998,18 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - turn_event_callout_callout_model = {} # TurnEventCalloutCallout + turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' - turn_event_callout_callout_model['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model['result_variable'] = 'testString' - turn_event_callout_error_model = {} # TurnEventCalloutError + turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model @@ -8144,7 +9034,8 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited """ @@ -8156,7 +9047,7 @@ def test_message_output_debug_turn_event_turn_event_handler_visited_serializatio # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8183,7 +9074,8 @@ def test_message_output_debug_turn_event_turn_event_handler_visited_serializatio message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited """ @@ -8195,7 +9087,7 @@ def test_message_output_debug_turn_event_turn_event_node_visited_serialization(s # Construct dict forms of any model objects needed in order to build this model. - turn_event_node_source_model = {} # TurnEventNodeSource + turn_event_node_source_model = {} # TurnEventNodeSource turn_event_node_source_model['type'] = 'dialog_node' turn_event_node_source_model['dialog_node'] = 'testString' turn_event_node_source_model['title'] = 'testString' @@ -8222,7 +9114,8 @@ def test_message_output_debug_turn_event_turn_event_node_visited_serialization(s message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventSearch(): + +class TestModel_MessageOutputDebugTurnEventTurnEventSearch: """ Test Class for MessageOutputDebugTurnEventTurnEventSearch """ @@ -8234,13 +9127,13 @@ def test_message_output_debug_turn_event_turn_event_search_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - turn_event_search_error_model = {} # TurnEventSearchError + turn_event_search_error_model = {} # TurnEventSearchError turn_event_search_error_model['message'] = 'testString' # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model @@ -8264,7 +9157,8 @@ def test_message_output_debug_turn_event_turn_event_search_serialization(self): message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered(): + +class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered: """ Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered """ @@ -8276,7 +9170,7 @@ def test_message_output_debug_turn_event_turn_event_step_answered_serialization( # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8305,7 +9199,8 @@ def test_message_output_debug_turn_event_turn_event_step_answered_serialization( message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventStepVisited """ @@ -8317,7 +9212,7 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8346,7 +9241,8 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio """ @@ -8358,7 +9254,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model @@ -8368,7 +9264,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -8386,7 +9282,8 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -8398,16 +9295,16 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model @@ -8432,7 +9329,8 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -8444,13 +9342,13 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model @@ -8478,7 +9376,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeDate """ @@ -8507,7 +9406,8 @@ def test_runtime_response_generic_runtime_response_type_date_serialization(self) runtime_response_generic_runtime_response_type_date_model_json2 = runtime_response_generic_runtime_response_type_date_model.to_dict() assert runtime_response_generic_runtime_response_type_date_model_json2 == runtime_response_generic_runtime_response_type_date_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe """ @@ -8519,7 +9419,7 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model @@ -8546,7 +9446,8 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -8558,7 +9459,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model @@ -8585,7 +9486,8 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -8597,16 +9499,16 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8634,14 +9536,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8652,28 +9554,29 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -8683,14 +9586,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model @@ -8717,7 +9620,8 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause: """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -8729,7 +9633,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model @@ -8754,7 +9658,8 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSearch(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSearch: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSearch """ @@ -8766,21 +9671,21 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model = {} # SearchResultMetadata search_result_metadata_model['confidence'] = 72.5 search_result_metadata_model['score'] = 72.5 - search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model = {} # SearchResultHighlight search_result_highlight_model['body'] = ['testString'] search_result_highlight_model['title'] = ['testString'] search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] - search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model = {} # SearchResultAnswer search_result_answer_model['text'] = 'testString' search_result_answer_model['confidence'] = 0 - search_result_model = {} # SearchResult + search_result_model = {} # SearchResult search_result_model['id'] = 'testString' search_result_model['result_metadata'] = search_result_metadata_model search_result_model['body'] = 'testString' @@ -8789,7 +9694,7 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel search_result_model['highlight'] = search_result_highlight_model search_result_model['answers'] = [search_result_answer_model] - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSearch model @@ -8815,7 +9720,8 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel runtime_response_generic_runtime_response_type_search_model_json2 = runtime_response_generic_runtime_response_type_search_model.to_dict() assert runtime_response_generic_runtime_response_type_search_model_json2 == runtime_response_generic_runtime_response_type_search_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -8827,16 +9733,16 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8864,14 +9770,14 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8882,28 +9788,29 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -8913,15 +9820,15 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model - dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'foo': 'bar'} + dialog_suggestion_model['output'] = {'anyKey': 'anyValue'} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model @@ -8946,7 +9853,8 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -8958,7 +9866,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model @@ -8982,7 +9890,8 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ @@ -8994,13 +9903,13 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -9018,7 +9927,8 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo """ @@ -9030,7 +9940,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model @@ -9040,7 +9950,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 945c28ba..0a154443 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2023. +# (C) Copyright IBM Corp. 2016, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -65,8 +65,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -74,7 +73,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestCreateEnvironment(): + +class TestCreateEnvironment: """ Test Class for create_environment """ @@ -87,11 +87,13 @@ def test_create_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -103,7 +105,7 @@ def test_create_environment_all_params(self): name, description=description, size=size, - headers={} + headers={}, ) # Check for correct operation @@ -132,11 +134,13 @@ def test_create_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -148,7 +152,7 @@ def test_create_environment_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_environment(**req_copy) @@ -161,7 +165,8 @@ def test_create_environment_value_error_with_retries(self): _service.disable_retries() self.test_create_environment_value_error() -class TestListEnvironments(): + +class TestListEnvironments: """ Test Class for list_environments """ @@ -174,11 +179,13 @@ def test_list_environments_all_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values name = 'testString' @@ -186,14 +193,14 @@ def test_list_environments_all_params(self): # Invoke method response = _service.list_environments( name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -214,16 +221,17 @@ def test_list_environments_required_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_environments() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -245,17 +253,19 @@ def test_list_environments_value_error(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_environments(**req_copy) @@ -268,7 +278,8 @@ def test_list_environments_value_error_with_retries(self): _service.disable_retries() self.test_list_environments_value_error() -class TestGetEnvironment(): + +class TestGetEnvironment: """ Test Class for get_environment """ @@ -281,11 +292,13 @@ def test_get_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -293,7 +306,7 @@ def test_get_environment_all_params(self): # Invoke method response = _service.get_environment( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -317,11 +330,13 @@ def test_get_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -331,7 +346,7 @@ def test_get_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_environment(**req_copy) @@ -344,7 +359,8 @@ def test_get_environment_value_error_with_retries(self): _service.disable_retries() self.test_get_environment_value_error() -class TestUpdateEnvironment(): + +class TestUpdateEnvironment: """ Test Class for update_environment """ @@ -357,11 +373,13 @@ def test_update_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -375,7 +393,7 @@ def test_update_environment_all_params(self): name=name, description=description, size=size, - headers={} + headers={}, ) # Check for correct operation @@ -404,11 +422,13 @@ def test_update_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -421,7 +441,7 @@ def test_update_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_environment(**req_copy) @@ -434,7 +454,8 @@ def test_update_environment_value_error_with_retries(self): _service.disable_retries() self.test_update_environment_value_error() -class TestDeleteEnvironment(): + +class TestDeleteEnvironment: """ Test Class for delete_environment """ @@ -447,11 +468,13 @@ def test_delete_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -459,7 +482,7 @@ def test_delete_environment_all_params(self): # Invoke method response = _service.delete_environment( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -483,11 +506,13 @@ def test_delete_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -497,7 +522,7 @@ def test_delete_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_environment(**req_copy) @@ -510,7 +535,8 @@ def test_delete_environment_value_error_with_retries(self): _service.disable_retries() self.test_delete_environment_value_error() -class TestListFields(): + +class TestListFields: """ Test Class for list_fields """ @@ -523,11 +549,13 @@ def test_list_fields_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -537,14 +565,14 @@ def test_list_fields_all_params(self): response = _service.list_fields( environment_id, collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -565,11 +593,13 @@ def test_list_fields_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -581,7 +611,7 @@ def test_list_fields_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_fields(**req_copy) @@ -594,6 +624,7 @@ def test_list_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_fields_value_error() + # endregion ############################################################################## # End of Service: Environments @@ -604,7 +635,8 @@ def test_list_fields_value_error_with_retries(self): ############################################################################## # region -class TestCreateConfiguration(): + +class TestCreateConfiguration: """ Test Class for create_configuration """ @@ -616,12 +648,14 @@ def test_create_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -734,7 +768,7 @@ def test_create_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -783,8 +817,8 @@ def test_create_configuration_all_params(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -827,7 +861,7 @@ def test_create_configuration_all_params(self): enrichments=enrichments, normalizations=normalizations, source=source, - headers={} + headers={}, ) # Check for correct operation @@ -858,12 +892,14 @@ def test_create_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -976,7 +1012,7 @@ def test_create_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1025,8 +1061,8 @@ def test_create_configuration_value_error(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1066,7 +1102,7 @@ def test_create_configuration_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_configuration(**req_copy) @@ -1079,7 +1115,8 @@ def test_create_configuration_value_error_with_retries(self): _service.disable_retries() self.test_create_configuration_value_error() -class TestListConfigurations(): + +class TestListConfigurations: """ Test Class for list_configurations """ @@ -1091,12 +1128,14 @@ def test_list_configurations_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1106,14 +1145,14 @@ def test_list_configurations_all_params(self): response = _service.list_configurations( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -1133,12 +1172,14 @@ def test_list_configurations_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1146,7 +1187,7 @@ def test_list_configurations_required_params(self): # Invoke method response = _service.list_configurations( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1169,12 +1210,14 @@ def test_list_configurations_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1184,7 +1227,7 @@ def test_list_configurations_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_configurations(**req_copy) @@ -1197,7 +1240,8 @@ def test_list_configurations_value_error_with_retries(self): _service.disable_retries() self.test_list_configurations_value_error() -class TestGetConfiguration(): + +class TestGetConfiguration: """ Test Class for get_configuration """ @@ -1209,12 +1253,14 @@ def test_get_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1224,7 +1270,7 @@ def test_get_configuration_all_params(self): response = _service.get_configuration( environment_id, configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -1247,12 +1293,14 @@ def test_get_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1264,7 +1312,7 @@ def test_get_configuration_value_error(self): "configuration_id": configuration_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_configuration(**req_copy) @@ -1277,7 +1325,8 @@ def test_get_configuration_value_error_with_retries(self): _service.disable_retries() self.test_get_configuration_value_error() -class TestUpdateConfiguration(): + +class TestUpdateConfiguration: """ Test Class for update_configuration """ @@ -1289,12 +1338,14 @@ def test_update_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -1407,7 +1458,7 @@ def test_update_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1456,8 +1507,8 @@ def test_update_configuration_all_params(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1502,7 +1553,7 @@ def test_update_configuration_all_params(self): enrichments=enrichments, normalizations=normalizations, source=source, - headers={} + headers={}, ) # Check for correct operation @@ -1533,12 +1584,14 @@ def test_update_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -1651,7 +1704,7 @@ def test_update_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1700,8 +1753,8 @@ def test_update_configuration_value_error(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1743,7 +1796,7 @@ def test_update_configuration_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_configuration(**req_copy) @@ -1756,7 +1809,8 @@ def test_update_configuration_value_error_with_retries(self): _service.disable_retries() self.test_update_configuration_value_error() -class TestDeleteConfiguration(): + +class TestDeleteConfiguration: """ Test Class for delete_configuration """ @@ -1769,11 +1823,13 @@ def test_delete_configuration_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1783,7 +1839,7 @@ def test_delete_configuration_all_params(self): response = _service.delete_configuration( environment_id, configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -1807,11 +1863,13 @@ def test_delete_configuration_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1823,7 +1881,7 @@ def test_delete_configuration_value_error(self): "configuration_id": configuration_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_configuration(**req_copy) @@ -1836,6 +1894,7 @@ def test_delete_configuration_value_error_with_retries(self): _service.disable_retries() self.test_delete_configuration_value_error() + # endregion ############################################################################## # End of Service: Configurations @@ -1846,7 +1905,8 @@ def test_delete_configuration_value_error_with_retries(self): ############################################################################## # region -class TestCreateCollection(): + +class TestCreateCollection: """ Test Class for create_collection """ @@ -1859,11 +1919,13 @@ def test_create_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -1879,7 +1941,7 @@ def test_create_collection_all_params(self): description=description, configuration_id=configuration_id, language=language, - headers={} + headers={}, ) # Check for correct operation @@ -1909,11 +1971,13 @@ def test_create_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -1928,7 +1992,7 @@ def test_create_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_collection(**req_copy) @@ -1941,7 +2005,8 @@ def test_create_collection_value_error_with_retries(self): _service.disable_retries() self.test_create_collection_value_error() -class TestListCollections(): + +class TestListCollections: """ Test Class for list_collections """ @@ -1954,11 +2019,13 @@ def test_list_collections_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1968,14 +2035,14 @@ def test_list_collections_all_params(self): response = _service.list_collections( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -1996,11 +2063,13 @@ def test_list_collections_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2008,7 +2077,7 @@ def test_list_collections_required_params(self): # Invoke method response = _service.list_collections( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -2032,11 +2101,13 @@ def test_list_collections_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2046,7 +2117,7 @@ def test_list_collections_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collections(**req_copy) @@ -2059,7 +2130,8 @@ def test_list_collections_value_error_with_retries(self): _service.disable_retries() self.test_list_collections_value_error() -class TestGetCollection(): + +class TestGetCollection: """ Test Class for get_collection """ @@ -2072,11 +2144,13 @@ def test_get_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2086,7 +2160,7 @@ def test_get_collection_all_params(self): response = _service.get_collection( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2110,11 +2184,13 @@ def test_get_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2126,7 +2202,7 @@ def test_get_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_collection(**req_copy) @@ -2139,7 +2215,8 @@ def test_get_collection_value_error_with_retries(self): _service.disable_retries() self.test_get_collection_value_error() -class TestUpdateCollection(): + +class TestUpdateCollection: """ Test Class for update_collection """ @@ -2152,11 +2229,13 @@ def test_update_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -2172,7 +2251,7 @@ def test_update_collection_all_params(self): name, description=description, configuration_id=configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -2201,11 +2280,13 @@ def test_update_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -2221,7 +2302,7 @@ def test_update_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_collection(**req_copy) @@ -2234,7 +2315,8 @@ def test_update_collection_value_error_with_retries(self): _service.disable_retries() self.test_update_collection_value_error() -class TestDeleteCollection(): + +class TestDeleteCollection: """ Test Class for delete_collection """ @@ -2247,11 +2329,13 @@ def test_delete_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2261,7 +2345,7 @@ def test_delete_collection_all_params(self): response = _service.delete_collection( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2285,11 +2369,13 @@ def test_delete_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2301,7 +2387,7 @@ def test_delete_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_collection(**req_copy) @@ -2314,7 +2400,8 @@ def test_delete_collection_value_error_with_retries(self): _service.disable_retries() self.test_delete_collection_value_error() -class TestListCollectionFields(): + +class TestListCollectionFields: """ Test Class for list_collection_fields """ @@ -2327,11 +2414,13 @@ def test_list_collection_fields_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2341,7 +2430,7 @@ def test_list_collection_fields_all_params(self): response = _service.list_collection_fields( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2365,11 +2454,13 @@ def test_list_collection_fields_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2381,7 +2472,7 @@ def test_list_collection_fields_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collection_fields(**req_copy) @@ -2394,6 +2485,7 @@ def test_list_collection_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_collection_fields_value_error() + # endregion ############################################################################## # End of Service: Collections @@ -2404,7 +2496,8 @@ def test_list_collection_fields_value_error_with_retries(self): ############################################################################## # region -class TestListExpansions(): + +class TestListExpansions: """ Test Class for list_expansions """ @@ -2417,11 +2510,13 @@ def test_list_expansions_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2431,7 +2526,7 @@ def test_list_expansions_all_params(self): response = _service.list_expansions( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2455,11 +2550,13 @@ def test_list_expansions_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2471,7 +2568,7 @@ def test_list_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_expansions(**req_copy) @@ -2484,7 +2581,8 @@ def test_list_expansions_value_error_with_retries(self): _service.disable_retries() self.test_list_expansions_value_error() -class TestCreateExpansions(): + +class TestCreateExpansions: """ Test Class for create_expansions """ @@ -2497,11 +2595,13 @@ def test_create_expansions_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2518,7 +2618,7 @@ def test_create_expansions_all_params(self): environment_id, collection_id, expansions, - headers={} + headers={}, ) # Check for correct operation @@ -2545,11 +2645,13 @@ def test_create_expansions_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2568,7 +2670,7 @@ def test_create_expansions_value_error(self): "expansions": expansions, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_expansions(**req_copy) @@ -2581,7 +2683,8 @@ def test_create_expansions_value_error_with_retries(self): _service.disable_retries() self.test_create_expansions_value_error() -class TestDeleteExpansions(): + +class TestDeleteExpansions: """ Test Class for delete_expansions """ @@ -2593,9 +2696,11 @@ def test_delete_expansions_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -2605,7 +2710,7 @@ def test_delete_expansions_all_params(self): response = _service.delete_expansions( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2628,9 +2733,11 @@ def test_delete_expansions_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -2642,7 +2749,7 @@ def test_delete_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_expansions(**req_copy) @@ -2655,7 +2762,8 @@ def test_delete_expansions_value_error_with_retries(self): _service.disable_retries() self.test_delete_expansions_value_error() -class TestGetTokenizationDictionaryStatus(): + +class TestGetTokenizationDictionaryStatus: """ Test Class for get_tokenization_dictionary_status """ @@ -2668,11 +2776,13 @@ def test_get_tokenization_dictionary_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2682,7 +2792,7 @@ def test_get_tokenization_dictionary_status_all_params(self): response = _service.get_tokenization_dictionary_status( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2706,11 +2816,13 @@ def test_get_tokenization_dictionary_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2722,7 +2834,7 @@ def test_get_tokenization_dictionary_status_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_tokenization_dictionary_status(**req_copy) @@ -2735,7 +2847,8 @@ def test_get_tokenization_dictionary_status_value_error_with_retries(self): _service.disable_retries() self.test_get_tokenization_dictionary_status_value_error() -class TestCreateTokenizationDictionary(): + +class TestCreateTokenizationDictionary: """ Test Class for create_tokenization_dictionary """ @@ -2748,11 +2861,13 @@ def test_create_tokenization_dictionary_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a TokenDictRule model token_dict_rule_model = {} @@ -2771,7 +2886,7 @@ def test_create_tokenization_dictionary_all_params(self): environment_id, collection_id, tokenization_rules=tokenization_rules, - headers={} + headers={}, ) # Check for correct operation @@ -2798,11 +2913,13 @@ def test_create_tokenization_dictionary_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -2812,7 +2929,7 @@ def test_create_tokenization_dictionary_required_params(self): response = _service.create_tokenization_dictionary( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2836,11 +2953,13 @@ def test_create_tokenization_dictionary_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -2852,7 +2971,7 @@ def test_create_tokenization_dictionary_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_tokenization_dictionary(**req_copy) @@ -2865,7 +2984,8 @@ def test_create_tokenization_dictionary_value_error_with_retries(self): _service.disable_retries() self.test_create_tokenization_dictionary_value_error() -class TestDeleteTokenizationDictionary(): + +class TestDeleteTokenizationDictionary: """ Test Class for delete_tokenization_dictionary """ @@ -2877,9 +2997,11 @@ def test_delete_tokenization_dictionary_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2889,7 +3011,7 @@ def test_delete_tokenization_dictionary_all_params(self): response = _service.delete_tokenization_dictionary( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2912,9 +3034,11 @@ def test_delete_tokenization_dictionary_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2926,7 +3050,7 @@ def test_delete_tokenization_dictionary_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_tokenization_dictionary(**req_copy) @@ -2939,7 +3063,8 @@ def test_delete_tokenization_dictionary_value_error_with_retries(self): _service.disable_retries() self.test_delete_tokenization_dictionary_value_error() -class TestGetStopwordListStatus(): + +class TestGetStopwordListStatus: """ Test Class for get_stopword_list_status """ @@ -2952,11 +3077,13 @@ def test_get_stopword_list_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2966,7 +3093,7 @@ def test_get_stopword_list_status_all_params(self): response = _service.get_stopword_list_status( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2990,11 +3117,13 @@ def test_get_stopword_list_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3006,7 +3135,7 @@ def test_get_stopword_list_status_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_stopword_list_status(**req_copy) @@ -3019,7 +3148,8 @@ def test_get_stopword_list_status_value_error_with_retries(self): _service.disable_retries() self.test_get_stopword_list_status_value_error() -class TestCreateStopwordList(): + +class TestCreateStopwordList: """ Test Class for create_stopword_list """ @@ -3032,11 +3162,13 @@ def test_create_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3050,7 +3182,7 @@ def test_create_stopword_list_all_params(self): collection_id, stopword_file, stopword_filename=stopword_filename, - headers={} + headers={}, ) # Check for correct operation @@ -3074,11 +3206,13 @@ def test_create_stopword_list_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3092,7 +3226,7 @@ def test_create_stopword_list_required_params(self): collection_id, stopword_file, stopword_filename=stopword_filename, - headers={} + headers={}, ) # Check for correct operation @@ -3116,11 +3250,13 @@ def test_create_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3135,7 +3271,7 @@ def test_create_stopword_list_value_error(self): "stopword_file": stopword_file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) @@ -3148,7 +3284,8 @@ def test_create_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_create_stopword_list_value_error() -class TestDeleteStopwordList(): + +class TestDeleteStopwordList: """ Test Class for delete_stopword_list """ @@ -3160,9 +3297,11 @@ def test_delete_stopword_list_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3172,7 +3311,7 @@ def test_delete_stopword_list_all_params(self): response = _service.delete_stopword_list( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3195,9 +3334,11 @@ def test_delete_stopword_list_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3209,7 +3350,7 @@ def test_delete_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) @@ -3222,6 +3363,7 @@ def test_delete_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_delete_stopword_list_value_error() + # endregion ############################################################################## # End of Service: QueryModifications @@ -3232,7 +3374,8 @@ def test_delete_stopword_list_value_error_with_retries(self): ############################################################################## # region -class TestAddDocument(): + +class TestAddDocument: """ Test Class for add_document """ @@ -3245,11 +3388,13 @@ def test_add_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3267,7 +3412,7 @@ def test_add_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -3291,11 +3436,13 @@ def test_add_document_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3305,7 +3452,7 @@ def test_add_document_required_params(self): response = _service.add_document( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3329,11 +3476,13 @@ def test_add_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3345,7 +3494,7 @@ def test_add_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_document(**req_copy) @@ -3358,7 +3507,8 @@ def test_add_document_value_error_with_retries(self): _service.disable_retries() self.test_add_document_value_error() -class TestGetDocumentStatus(): + +class TestGetDocumentStatus: """ Test Class for get_document_status """ @@ -3371,11 +3521,13 @@ def test_get_document_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3387,7 +3539,7 @@ def test_get_document_status_all_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3411,11 +3563,13 @@ def test_get_document_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3429,7 +3583,7 @@ def test_get_document_status_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_status(**req_copy) @@ -3442,7 +3596,8 @@ def test_get_document_status_value_error_with_retries(self): _service.disable_retries() self.test_get_document_status_value_error() -class TestUpdateDocument(): + +class TestUpdateDocument: """ Test Class for update_document """ @@ -3455,11 +3610,13 @@ def test_update_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3479,7 +3636,7 @@ def test_update_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -3503,11 +3660,13 @@ def test_update_document_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3519,7 +3678,7 @@ def test_update_document_required_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3543,11 +3702,13 @@ def test_update_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3561,7 +3722,7 @@ def test_update_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document(**req_copy) @@ -3574,7 +3735,8 @@ def test_update_document_value_error_with_retries(self): _service.disable_retries() self.test_update_document_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -3587,11 +3749,13 @@ def test_delete_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3603,7 +3767,7 @@ def test_delete_document_all_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3627,11 +3791,13 @@ def test_delete_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3645,7 +3811,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -3658,6 +3824,7 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() + # endregion ############################################################################## # End of Service: Documents @@ -3668,7 +3835,8 @@ def test_delete_document_value_error_with_retries(self): ############################################################################## # region -class TestQuery(): + +class TestQuery: """ Test Class for query """ @@ -3681,11 +3849,13 @@ def test_query_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3695,14 +3865,14 @@ def test_query_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -3737,7 +3907,7 @@ def test_query_all_params(self): bias=bias, spelling_suggestions=spelling_suggestions, x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -3750,14 +3920,14 @@ def test_query_all_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -3783,11 +3953,13 @@ def test_query_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3797,7 +3969,7 @@ def test_query_required_params(self): response = _service.query( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3821,11 +3993,13 @@ def test_query_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3837,7 +4011,7 @@ def test_query_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query(**req_copy) @@ -3850,7 +4024,8 @@ def test_query_value_error_with_retries(self): _service.disable_retries() self.test_query_value_error() -class TestQueryNotices(): + +class TestQueryNotices: """ Test Class for query_notices """ @@ -3863,11 +4038,13 @@ def test_query_notices_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3877,14 +4054,14 @@ def test_query_notices_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = ['testString'] offset = 38 sort = ['testString'] highlight = False passages_fields = ['testString'] - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate_field = 'testString' similar = False similar_document_ids = ['testString'] @@ -3911,14 +4088,14 @@ def test_query_notices_all_params(self): similar=similar, similar_document_ids=similar_document_ids, similar_fields=similar_fields, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -3955,11 +4132,13 @@ def test_query_notices_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3969,7 +4148,7 @@ def test_query_notices_required_params(self): response = _service.query_notices( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3993,11 +4172,13 @@ def test_query_notices_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4009,7 +4190,7 @@ def test_query_notices_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_notices(**req_copy) @@ -4022,7 +4203,8 @@ def test_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_notices_value_error() -class TestFederatedQuery(): + +class TestFederatedQuery: """ Test Class for federated_query """ @@ -4035,11 +4217,13 @@ def test_federated_query_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4049,14 +4233,14 @@ def test_federated_query_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4089,7 +4273,7 @@ def test_federated_query_all_params(self): similar_fields=similar_fields, bias=bias, x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -4103,14 +4287,14 @@ def test_federated_query_all_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -4135,11 +4319,13 @@ def test_federated_query_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4149,14 +4335,14 @@ def test_federated_query_required_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4187,7 +4373,7 @@ def test_federated_query_required_params(self): similar_document_ids=similar_document_ids, similar_fields=similar_fields, bias=bias, - headers={} + headers={}, ) # Check for correct operation @@ -4201,14 +4387,14 @@ def test_federated_query_required_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -4233,11 +4419,13 @@ def test_federated_query_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4247,14 +4435,14 @@ def test_federated_query_value_error(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4268,7 +4456,7 @@ def test_federated_query_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.federated_query(**req_copy) @@ -4281,7 +4469,8 @@ def test_federated_query_value_error_with_retries(self): _service.disable_retries() self.test_federated_query_value_error() -class TestFederatedQueryNotices(): + +class TestFederatedQueryNotices: """ Test Class for federated_query_notices """ @@ -4294,11 +4483,13 @@ def test_federated_query_notices_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4307,7 +4498,7 @@ def test_federated_query_notices_all_params(self): query = 'testString' natural_language_query = 'testString' aggregation = 'testString' - count = 38 + count = 10 return_ = ['testString'] offset = 38 sort = ['testString'] @@ -4334,14 +4525,14 @@ def test_federated_query_notices_all_params(self): similar=similar, similar_document_ids=similar_document_ids, similar_fields=similar_fields, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string assert 'filter={}'.format(filter) in query_string @@ -4375,11 +4566,13 @@ def test_federated_query_notices_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4389,14 +4582,14 @@ def test_federated_query_notices_required_params(self): response = _service.federated_query_notices( environment_id, collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -4417,11 +4610,13 @@ def test_federated_query_notices_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4433,7 +4628,7 @@ def test_federated_query_notices_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.federated_query_notices(**req_copy) @@ -4446,7 +4641,8 @@ def test_federated_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_federated_query_notices_value_error() -class TestGetAutocompletion(): + +class TestGetAutocompletion: """ Test Class for get_autocompletion """ @@ -4459,18 +4655,20 @@ def test_get_autocompletion_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' collection_id = 'testString' prefix = 'testString' field = 'testString' - count = 38 + count = 5 # Invoke method response = _service.get_autocompletion( @@ -4479,14 +4677,14 @@ def test_get_autocompletion_all_params(self): prefix, field=field, count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string assert 'field={}'.format(field) in query_string @@ -4509,11 +4707,13 @@ def test_get_autocompletion_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4525,14 +4725,14 @@ def test_get_autocompletion_required_params(self): environment_id, collection_id, prefix, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string @@ -4553,11 +4753,13 @@ def test_get_autocompletion_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4571,7 +4773,7 @@ def test_get_autocompletion_value_error(self): "prefix": prefix, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) @@ -4584,6 +4786,7 @@ def test_get_autocompletion_value_error_with_retries(self): _service.disable_retries() self.test_get_autocompletion_value_error() + # endregion ############################################################################## # End of Service: Queries @@ -4594,7 +4797,8 @@ def test_get_autocompletion_value_error_with_retries(self): ############################################################################## # region -class TestListTrainingData(): + +class TestListTrainingData: """ Test Class for list_training_data """ @@ -4607,11 +4811,13 @@ def test_list_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4621,7 +4827,7 @@ def test_list_training_data_all_params(self): response = _service.list_training_data( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -4645,11 +4851,13 @@ def test_list_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4661,7 +4869,7 @@ def test_list_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_data(**req_copy) @@ -4674,7 +4882,8 @@ def test_list_training_data_value_error_with_retries(self): _service.disable_retries() self.test_list_training_data_value_error() -class TestAddTrainingData(): + +class TestAddTrainingData: """ Test Class for add_training_data """ @@ -4687,11 +4896,13 @@ def test_add_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -4713,7 +4924,7 @@ def test_add_training_data_all_params(self): natural_language_query=natural_language_query, filter=filter, examples=examples, - headers={} + headers={}, ) # Check for correct operation @@ -4742,11 +4953,13 @@ def test_add_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -4767,7 +4980,7 @@ def test_add_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_training_data(**req_copy) @@ -4780,7 +4993,8 @@ def test_add_training_data_value_error_with_retries(self): _service.disable_retries() self.test_add_training_data_value_error() -class TestDeleteAllTrainingData(): + +class TestDeleteAllTrainingData: """ Test Class for delete_all_training_data """ @@ -4792,9 +5006,11 @@ def test_delete_all_training_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4804,7 +5020,7 @@ def test_delete_all_training_data_all_params(self): response = _service.delete_all_training_data( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -4827,9 +5043,11 @@ def test_delete_all_training_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4841,7 +5059,7 @@ def test_delete_all_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_all_training_data(**req_copy) @@ -4854,7 +5072,8 @@ def test_delete_all_training_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_all_training_data_value_error() -class TestGetTrainingData(): + +class TestGetTrainingData: """ Test Class for get_training_data """ @@ -4867,11 +5086,13 @@ def test_get_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4883,7 +5104,7 @@ def test_get_training_data_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -4907,11 +5128,13 @@ def test_get_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4925,7 +5148,7 @@ def test_get_training_data_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_data(**req_copy) @@ -4938,7 +5161,8 @@ def test_get_training_data_value_error_with_retries(self): _service.disable_retries() self.test_get_training_data_value_error() -class TestDeleteTrainingData(): + +class TestDeleteTrainingData: """ Test Class for delete_training_data """ @@ -4950,9 +5174,11 @@ def test_delete_training_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4964,7 +5190,7 @@ def test_delete_training_data_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -4987,9 +5213,11 @@ def test_delete_training_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5003,7 +5231,7 @@ def test_delete_training_data_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_data(**req_copy) @@ -5016,7 +5244,8 @@ def test_delete_training_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_data_value_error() -class TestListTrainingExamples(): + +class TestListTrainingExamples: """ Test Class for list_training_examples """ @@ -5029,11 +5258,13 @@ def test_list_training_examples_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5045,7 +5276,7 @@ def test_list_training_examples_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -5069,11 +5300,13 @@ def test_list_training_examples_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5087,7 +5320,7 @@ def test_list_training_examples_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_examples(**req_copy) @@ -5100,7 +5333,8 @@ def test_list_training_examples_value_error_with_retries(self): _service.disable_retries() self.test_list_training_examples_value_error() -class TestCreateTrainingExample(): + +class TestCreateTrainingExample: """ Test Class for create_training_example """ @@ -5113,11 +5347,13 @@ def test_create_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -5135,7 +5371,7 @@ def test_create_training_example_all_params(self): document_id=document_id, cross_reference=cross_reference, relevance=relevance, - headers={} + headers={}, ) # Check for correct operation @@ -5164,11 +5400,13 @@ def test_create_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -5185,7 +5423,7 @@ def test_create_training_example_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_training_example(**req_copy) @@ -5198,7 +5436,8 @@ def test_create_training_example_value_error_with_retries(self): _service.disable_retries() self.test_create_training_example_value_error() -class TestDeleteTrainingExample(): + +class TestDeleteTrainingExample: """ Test Class for delete_training_example """ @@ -5210,9 +5449,11 @@ def test_delete_training_example_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5226,7 +5467,7 @@ def test_delete_training_example_all_params(self): collection_id, query_id, example_id, - headers={} + headers={}, ) # Check for correct operation @@ -5249,9 +5490,11 @@ def test_delete_training_example_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5267,7 +5510,7 @@ def test_delete_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_example(**req_copy) @@ -5280,7 +5523,8 @@ def test_delete_training_example_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_example_value_error() -class TestUpdateTrainingExample(): + +class TestUpdateTrainingExample: """ Test Class for update_training_example """ @@ -5293,11 +5537,13 @@ def test_update_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5315,7 +5561,7 @@ def test_update_training_example_all_params(self): example_id, cross_reference=cross_reference, relevance=relevance, - headers={} + headers={}, ) # Check for correct operation @@ -5343,11 +5589,13 @@ def test_update_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5365,7 +5613,7 @@ def test_update_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_training_example(**req_copy) @@ -5378,7 +5626,8 @@ def test_update_training_example_value_error_with_retries(self): _service.disable_retries() self.test_update_training_example_value_error() -class TestGetTrainingExample(): + +class TestGetTrainingExample: """ Test Class for get_training_example """ @@ -5391,11 +5640,13 @@ def test_get_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5409,7 +5660,7 @@ def test_get_training_example_all_params(self): collection_id, query_id, example_id, - headers={} + headers={}, ) # Check for correct operation @@ -5433,11 +5684,13 @@ def test_get_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5453,7 +5706,7 @@ def test_get_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_example(**req_copy) @@ -5466,6 +5719,7 @@ def test_get_training_example_value_error_with_retries(self): _service.disable_retries() self.test_get_training_example_value_error() + # endregion ############################################################################## # End of Service: TrainingData @@ -5476,7 +5730,8 @@ def test_get_training_example_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -5488,9 +5743,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5498,14 +5755,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -5525,9 +5782,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5537,7 +5796,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -5550,6 +5809,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -5560,7 +5820,8 @@ def test_delete_user_data_value_error_with_retries(self): ############################################################################## # region -class TestCreateEvent(): + +class TestCreateEvent: """ Test Class for create_event """ @@ -5573,11 +5834,13 @@ def test_create_event_all_params(self): # Set up mock url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EventData model event_data_model = {} @@ -5596,7 +5859,7 @@ def test_create_event_all_params(self): response = _service.create_event( type, data, - headers={} + headers={}, ) # Check for correct operation @@ -5624,11 +5887,13 @@ def test_create_event_value_error(self): # Set up mock url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EventData model event_data_model = {} @@ -5649,7 +5914,7 @@ def test_create_event_value_error(self): "data": data, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_event(**req_copy) @@ -5662,7 +5927,8 @@ def test_create_event_value_error_with_retries(self): _service.disable_retries() self.test_create_event_value_error() -class TestQueryLog(): + +class TestQueryLog: """ Test Class for query_log """ @@ -5675,16 +5941,18 @@ def test_query_log_all_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' query = 'testString' - count = 38 + count = 10 offset = 38 sort = ['testString'] @@ -5695,14 +5963,14 @@ def test_query_log_all_params(self): count=count, offset=offset, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -5727,16 +5995,17 @@ def test_query_log_required_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.query_log() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5758,17 +6027,19 @@ def test_query_log_value_error(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_log(**req_copy) @@ -5781,7 +6052,8 @@ def test_query_log_value_error_with_retries(self): _service.disable_retries() self.test_query_log_value_error() -class TestGetMetricsQuery(): + +class TestGetMetricsQuery: """ Test Class for get_metrics_query """ @@ -5794,11 +6066,13 @@ def test_get_metrics_query_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -5810,14 +6084,14 @@ def test_get_metrics_query_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -5838,16 +6112,17 @@ def test_get_metrics_query_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5869,17 +6144,19 @@ def test_get_metrics_query_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query(**req_copy) @@ -5892,7 +6169,8 @@ def test_get_metrics_query_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_value_error() -class TestGetMetricsQueryEvent(): + +class TestGetMetricsQueryEvent: """ Test Class for get_metrics_query_event """ @@ -5905,11 +6183,13 @@ def test_get_metrics_query_event_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -5921,14 +6201,14 @@ def test_get_metrics_query_event_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -5949,16 +6229,17 @@ def test_get_metrics_query_event_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_event() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5980,17 +6261,19 @@ def test_get_metrics_query_event_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_event(**req_copy) @@ -6003,7 +6286,8 @@ def test_get_metrics_query_event_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_event_value_error() -class TestGetMetricsQueryNoResults(): + +class TestGetMetricsQueryNoResults: """ Test Class for get_metrics_query_no_results """ @@ -6016,11 +6300,13 @@ def test_get_metrics_query_no_results_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -6032,14 +6318,14 @@ def test_get_metrics_query_no_results_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -6060,16 +6346,17 @@ def test_get_metrics_query_no_results_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_no_results() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6091,17 +6378,19 @@ def test_get_metrics_query_no_results_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_no_results(**req_copy) @@ -6114,7 +6403,8 @@ def test_get_metrics_query_no_results_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_no_results_value_error() -class TestGetMetricsEventRate(): + +class TestGetMetricsEventRate: """ Test Class for get_metrics_event_rate """ @@ -6127,11 +6417,13 @@ def test_get_metrics_event_rate_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -6143,14 +6435,14 @@ def test_get_metrics_event_rate_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -6171,16 +6463,17 @@ def test_get_metrics_event_rate_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_event_rate() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6202,17 +6495,19 @@ def test_get_metrics_event_rate_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_event_rate(**req_copy) @@ -6225,7 +6520,8 @@ def test_get_metrics_event_rate_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_event_rate_value_error() -class TestGetMetricsQueryTokenEvent(): + +class TestGetMetricsQueryTokenEvent: """ Test Class for get_metrics_query_token_event """ @@ -6238,26 +6534,28 @@ def test_get_metrics_query_token_event_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - count = 38 + count = 10 # Invoke method response = _service.get_metrics_query_token_event( count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string @@ -6278,16 +6576,17 @@ def test_get_metrics_query_token_event_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_token_event() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6309,17 +6608,19 @@ def test_get_metrics_query_token_event_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_token_event(**req_copy) @@ -6332,6 +6633,7 @@ def test_get_metrics_query_token_event_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_token_event_value_error() + # endregion ############################################################################## # End of Service: EventsAndFeedback @@ -6342,7 +6644,8 @@ def test_get_metrics_query_token_event_value_error_with_retries(self): ############################################################################## # region -class TestListCredentials(): + +class TestListCredentials: """ Test Class for list_credentials """ @@ -6355,11 +6658,13 @@ def test_list_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6367,7 +6672,7 @@ def test_list_credentials_all_params(self): # Invoke method response = _service.list_credentials( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -6391,11 +6696,13 @@ def test_list_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6405,7 +6712,7 @@ def test_list_credentials_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_credentials(**req_copy) @@ -6418,7 +6725,8 @@ def test_list_credentials_value_error_with_retries(self): _service.disable_retries() self.test_list_credentials_value_error() -class TestCreateCredentials(): + +class TestCreateCredentials: """ Test Class for create_credentials """ @@ -6431,11 +6739,13 @@ def test_create_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6476,7 +6786,7 @@ def test_create_credentials_all_params(self): source_type=source_type, credential_details=credential_details, status=status, - headers={} + headers={}, ) # Check for correct operation @@ -6505,11 +6815,13 @@ def test_create_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6549,7 +6861,7 @@ def test_create_credentials_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_credentials(**req_copy) @@ -6562,7 +6874,8 @@ def test_create_credentials_value_error_with_retries(self): _service.disable_retries() self.test_create_credentials_value_error() -class TestGetCredentials(): + +class TestGetCredentials: """ Test Class for get_credentials """ @@ -6575,11 +6888,13 @@ def test_get_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6589,7 +6904,7 @@ def test_get_credentials_all_params(self): response = _service.get_credentials( environment_id, credential_id, - headers={} + headers={}, ) # Check for correct operation @@ -6613,11 +6928,13 @@ def test_get_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6629,7 +6946,7 @@ def test_get_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_credentials(**req_copy) @@ -6642,7 +6959,8 @@ def test_get_credentials_value_error_with_retries(self): _service.disable_retries() self.test_get_credentials_value_error() -class TestUpdateCredentials(): + +class TestUpdateCredentials: """ Test Class for update_credentials """ @@ -6655,11 +6973,13 @@ def test_update_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6702,7 +7022,7 @@ def test_update_credentials_all_params(self): source_type=source_type, credential_details=credential_details, status=status, - headers={} + headers={}, ) # Check for correct operation @@ -6731,11 +7051,13 @@ def test_update_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6777,7 +7099,7 @@ def test_update_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_credentials(**req_copy) @@ -6790,7 +7112,8 @@ def test_update_credentials_value_error_with_retries(self): _service.disable_retries() self.test_update_credentials_value_error() -class TestDeleteCredentials(): + +class TestDeleteCredentials: """ Test Class for delete_credentials """ @@ -6803,11 +7126,13 @@ def test_delete_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6817,7 +7142,7 @@ def test_delete_credentials_all_params(self): response = _service.delete_credentials( environment_id, credential_id, - headers={} + headers={}, ) # Check for correct operation @@ -6841,11 +7166,13 @@ def test_delete_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6857,7 +7184,7 @@ def test_delete_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_credentials(**req_copy) @@ -6870,6 +7197,7 @@ def test_delete_credentials_value_error_with_retries(self): _service.disable_retries() self.test_delete_credentials_value_error() + # endregion ############################################################################## # End of Service: Credentials @@ -6880,7 +7208,8 @@ def test_delete_credentials_value_error_with_retries(self): ############################################################################## # region -class TestListGateways(): + +class TestListGateways: """ Test Class for list_gateways """ @@ -6893,11 +7222,13 @@ def test_list_gateways_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6905,7 +7236,7 @@ def test_list_gateways_all_params(self): # Invoke method response = _service.list_gateways( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -6929,11 +7260,13 @@ def test_list_gateways_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6943,7 +7276,7 @@ def test_list_gateways_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_gateways(**req_copy) @@ -6956,7 +7289,8 @@ def test_list_gateways_value_error_with_retries(self): _service.disable_retries() self.test_list_gateways_value_error() -class TestCreateGateway(): + +class TestCreateGateway: """ Test Class for create_gateway """ @@ -6969,11 +7303,13 @@ def test_create_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6983,7 +7319,7 @@ def test_create_gateway_all_params(self): response = _service.create_gateway( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation @@ -7010,11 +7346,13 @@ def test_create_gateway_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7022,7 +7360,7 @@ def test_create_gateway_required_params(self): # Invoke method response = _service.create_gateway( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -7046,11 +7384,13 @@ def test_create_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7060,7 +7400,7 @@ def test_create_gateway_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_gateway(**req_copy) @@ -7073,7 +7413,8 @@ def test_create_gateway_value_error_with_retries(self): _service.disable_retries() self.test_create_gateway_value_error() -class TestGetGateway(): + +class TestGetGateway: """ Test Class for get_gateway """ @@ -7086,11 +7427,13 @@ def test_get_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7100,7 +7443,7 @@ def test_get_gateway_all_params(self): response = _service.get_gateway( environment_id, gateway_id, - headers={} + headers={}, ) # Check for correct operation @@ -7124,11 +7467,13 @@ def test_get_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7140,7 +7485,7 @@ def test_get_gateway_value_error(self): "gateway_id": gateway_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_gateway(**req_copy) @@ -7153,7 +7498,8 @@ def test_get_gateway_value_error_with_retries(self): _service.disable_retries() self.test_get_gateway_value_error() -class TestDeleteGateway(): + +class TestDeleteGateway: """ Test Class for delete_gateway """ @@ -7166,11 +7512,13 @@ def test_delete_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7180,7 +7528,7 @@ def test_delete_gateway_all_params(self): response = _service.delete_gateway( environment_id, gateway_id, - headers={} + headers={}, ) # Check for correct operation @@ -7204,11 +7552,13 @@ def test_delete_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7220,7 +7570,7 @@ def test_delete_gateway_value_error(self): "gateway_id": gateway_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_gateway(**req_copy) @@ -7233,6 +7583,7 @@ def test_delete_gateway_value_error_with_retries(self): _service.disable_retries() self.test_delete_gateway_value_error() + # endregion ############################################################################## # End of Service: GatewayConfiguration @@ -7243,7 +7594,9 @@ def test_delete_gateway_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_Collection(): + + +class TestModel_Collection: """ Test Class for Collection """ @@ -7255,11 +7608,11 @@ def test_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_counts_model = {} # DocumentCounts + document_counts_model = {} # DocumentCounts - collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model = {} # CollectionDiskUsage - training_status_model = {} # TrainingStatus + training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 0 training_status_model['available'] = False training_status_model['processing'] = False @@ -7270,18 +7623,18 @@ def test_collection_serialization(self): training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'complete' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 5 - sdu_status_model = {} # SduStatus + sdu_status_model = {} # SduStatus sdu_status_model['enabled'] = True sdu_status_model['total_annotated_pages'] = 0 sdu_status_model['total_pages'] = 0 @@ -7315,7 +7668,8 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestModel_CollectionCrawlStatus(): + +class TestModel_CollectionCrawlStatus: """ Test Class for CollectionCrawlStatus """ @@ -7327,7 +7681,7 @@ def test_collection_crawl_status_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'running' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' @@ -7350,7 +7704,8 @@ def test_collection_crawl_status_serialization(self): collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() assert collection_crawl_status_model_json2 == collection_crawl_status_model_json -class TestModel_CollectionDiskUsage(): + +class TestModel_CollectionDiskUsage: """ Test Class for CollectionDiskUsage """ @@ -7378,7 +7733,8 @@ def test_collection_disk_usage_serialization(self): collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() assert collection_disk_usage_model_json2 == collection_disk_usage_model_json -class TestModel_CollectionUsage(): + +class TestModel_CollectionUsage: """ Test Class for CollectionUsage """ @@ -7406,7 +7762,8 @@ def test_collection_usage_serialization(self): collection_usage_model_json2 = collection_usage_model.to_dict() assert collection_usage_model_json2 == collection_usage_model_json -class TestModel_Completions(): + +class TestModel_Completions: """ Test Class for Completions """ @@ -7435,7 +7792,8 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestModel_Configuration(): + +class TestModel_Configuration: """ Test Class for Configuration """ @@ -7447,7 +7805,7 @@ def test_configuration_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -7455,27 +7813,27 @@ def test_configuration_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['span'] html_settings_model['keep_content'] = x_path_patterns_model @@ -7483,17 +7841,17 @@ def test_configuration_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = True segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'move' normalization_operation_model['source_field'] = 'extracted_metadata.title' normalization_operation_model['destination_field'] = 'metadata.title' - conversions_model = {} # Conversions + conversions_model = {} # Conversions conversions_model['pdf'] = pdf_settings_model conversions_model['word'] = word_settings_model conversions_model['html'] = html_settings_model @@ -7501,12 +7859,12 @@ def test_configuration_serialization(self): conversions_model['json_normalizations'] = [normalization_operation_model] conversions_model['image_text_recognition'] = True - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = False nlu_enrichment_keywords_model['limit'] = 50 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = False nlu_enrichment_entities_model['limit'] = 50 @@ -7515,41 +7873,41 @@ def test_configuration_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'WKS-model-id' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['IBM', 'Watson'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['IBM', 'Watson'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 50 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'WKS-model-id' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 8 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' - enrichment_model = {} # Enrichment + enrichment_model = {} # Enrichment enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'enriched_title' enrichment_model['source_field'] = 'title' @@ -7558,39 +7916,39 @@ def test_configuration_serialization(self): enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'weekly' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = '/sites/TestSiteA' source_options_site_coll_model['limit'] = 10 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -7598,7 +7956,7 @@ def test_configuration_serialization(self): source_options_model['buckets'] = [source_options_buckets_model] source_options_model['crawl_all_buckets'] = True - source_model = {} # Source + source_model = {} # Source source_model['type'] = 'salesforce' source_model['credential_id'] = '00ad0000-0000-11e8-ba89-0ed5f00f718b' source_model['schedule'] = source_schedule_model @@ -7628,7 +7986,8 @@ def test_configuration_serialization(self): configuration_model_json2 = configuration_model.to_dict() assert configuration_model_json2 == configuration_model_json -class TestModel_Conversions(): + +class TestModel_Conversions: """ Test Class for Conversions """ @@ -7640,7 +7999,7 @@ def test_conversions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -7648,27 +8007,27 @@ def test_conversions_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['testString'] html_settings_model['keep_content'] = x_path_patterns_model @@ -7676,12 +8035,12 @@ def test_conversions_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = False segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'copy' normalization_operation_model['source_field'] = 'testString' normalization_operation_model['destination_field'] = 'testString' @@ -7710,7 +8069,8 @@ def test_conversions_serialization(self): conversions_model_json2 = conversions_model.to_dict() assert conversions_model_json2 == conversions_model_json -class TestModel_CreateEventResponse(): + +class TestModel_CreateEventResponse: """ Test Class for CreateEventResponse """ @@ -7722,7 +8082,7 @@ def test_create_event_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - event_data_model = {} # EventData + event_data_model = {} # EventData event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' @@ -7750,7 +8110,8 @@ def test_create_event_response_serialization(self): create_event_response_model_json2 = create_event_response_model.to_dict() assert create_event_response_model_json2 == create_event_response_model_json -class TestModel_CredentialDetails(): + +class TestModel_CredentialDetails: """ Test Class for CredentialDetails """ @@ -7797,7 +8158,8 @@ def test_credential_details_serialization(self): credential_details_model_json2 = credential_details_model.to_dict() assert credential_details_model_json2 == credential_details_model_json -class TestModel_Credentials(): + +class TestModel_Credentials: """ Test Class for Credentials """ @@ -7809,7 +8171,7 @@ def test_credentials_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - credential_details_model = {} # CredentialDetails + credential_details_model = {} # CredentialDetails credential_details_model['credential_type'] = 'username_password' credential_details_model['client_id'] = 'testString' credential_details_model['enterprise_id'] = 'testString' @@ -7830,7 +8192,7 @@ def test_credentials_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' - status_details_model = {} # StatusDetails + status_details_model = {} # StatusDetails status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' @@ -7855,7 +8217,8 @@ def test_credentials_serialization(self): credentials_model_json2 = credentials_model.to_dict() assert credentials_model_json2 == credentials_model_json -class TestModel_CredentialsList(): + +class TestModel_CredentialsList: """ Test Class for CredentialsList """ @@ -7867,7 +8230,7 @@ def test_credentials_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - credential_details_model = {} # CredentialDetails + credential_details_model = {} # CredentialDetails credential_details_model['credential_type'] = 'username_password' credential_details_model['client_id'] = 'testString' credential_details_model['enterprise_id'] = 'testString' @@ -7888,11 +8251,11 @@ def test_credentials_list_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' - status_details_model = {} # StatusDetails + status_details_model = {} # StatusDetails status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' - credentials_model = {} # Credentials + credentials_model = {} # Credentials credentials_model['source_type'] = 'salesforce' credentials_model['credential_details'] = credential_details_model credentials_model['status'] = status_details_model @@ -7916,7 +8279,8 @@ def test_credentials_list_serialization(self): credentials_list_model_json2 = credentials_list_model.to_dict() assert credentials_list_model_json2 == credentials_list_model_json -class TestModel_DeleteCollectionResponse(): + +class TestModel_DeleteCollectionResponse: """ Test Class for DeleteCollectionResponse """ @@ -7946,7 +8310,8 @@ def test_delete_collection_response_serialization(self): delete_collection_response_model_json2 = delete_collection_response_model.to_dict() assert delete_collection_response_model_json2 == delete_collection_response_model_json -class TestModel_DeleteConfigurationResponse(): + +class TestModel_DeleteConfigurationResponse: """ Test Class for DeleteConfigurationResponse """ @@ -7958,7 +8323,7 @@ def test_delete_configuration_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a DeleteConfigurationResponse model delete_configuration_response_model_json = {} @@ -7981,7 +8346,8 @@ def test_delete_configuration_response_serialization(self): delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() assert delete_configuration_response_model_json2 == delete_configuration_response_model_json -class TestModel_DeleteCredentials(): + +class TestModel_DeleteCredentials: """ Test Class for DeleteCredentials """ @@ -8011,7 +8377,8 @@ def test_delete_credentials_serialization(self): delete_credentials_model_json2 = delete_credentials_model.to_dict() assert delete_credentials_model_json2 == delete_credentials_model_json -class TestModel_DeleteDocumentResponse(): + +class TestModel_DeleteDocumentResponse: """ Test Class for DeleteDocumentResponse """ @@ -8041,7 +8408,8 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestModel_DeleteEnvironmentResponse(): + +class TestModel_DeleteEnvironmentResponse: """ Test Class for DeleteEnvironmentResponse """ @@ -8071,7 +8439,8 @@ def test_delete_environment_response_serialization(self): delete_environment_response_model_json2 = delete_environment_response_model.to_dict() assert delete_environment_response_model_json2 == delete_environment_response_model_json -class TestModel_DiskUsage(): + +class TestModel_DiskUsage: """ Test Class for DiskUsage """ @@ -8099,7 +8468,8 @@ def test_disk_usage_serialization(self): disk_usage_model_json2 = disk_usage_model.to_dict() assert disk_usage_model_json2 == disk_usage_model_json -class TestModel_DocumentAccepted(): + +class TestModel_DocumentAccepted: """ Test Class for DocumentAccepted """ @@ -8111,7 +8481,7 @@ def test_document_accepted_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a DocumentAccepted model document_accepted_model_json = {} @@ -8134,7 +8504,8 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestModel_DocumentCounts(): + +class TestModel_DocumentCounts: """ Test Class for DocumentCounts """ @@ -8162,7 +8533,8 @@ def test_document_counts_serialization(self): document_counts_model_json2 = document_counts_model.to_dict() assert document_counts_model_json2 == document_counts_model_json -class TestModel_DocumentStatus(): + +class TestModel_DocumentStatus: """ Test Class for DocumentStatus """ @@ -8193,7 +8565,8 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestModel_Enrichment(): + +class TestModel_Enrichment: """ Test Class for Enrichment """ @@ -8205,12 +8578,12 @@ def test_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8219,36 +8592,36 @@ def test_enrichment_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' @@ -8278,7 +8651,8 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestModel_EnrichmentOptions(): + +class TestModel_EnrichmentOptions: """ Test Class for EnrichmentOptions """ @@ -8290,12 +8664,12 @@ def test_enrichment_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8304,31 +8678,31 @@ def test_enrichment_options_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8354,7 +8728,8 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestModel_Environment(): + +class TestModel_Environment: """ Test Class for Environment """ @@ -8366,18 +8741,18 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage - index_capacity_model = {} # IndexCapacity + index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model index_capacity_model['disk_usage'] = disk_usage_model index_capacity_model['collections'] = collection_usage_model - search_status_model = {} # SearchStatus + search_status_model = {} # SearchStatus search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' @@ -8407,7 +8782,8 @@ def test_environment_serialization(self): environment_model_json2 = environment_model.to_dict() assert environment_model_json2 == environment_model_json -class TestModel_EnvironmentDocuments(): + +class TestModel_EnvironmentDocuments: """ Test Class for EnvironmentDocuments """ @@ -8435,7 +8811,8 @@ def test_environment_documents_serialization(self): environment_documents_model_json2 = environment_documents_model.to_dict() assert environment_documents_model_json2 == environment_documents_model_json -class TestModel_EventData(): + +class TestModel_EventData: """ Test Class for EventData """ @@ -8469,7 +8846,8 @@ def test_event_data_serialization(self): event_data_model_json2 = event_data_model.to_dict() assert event_data_model_json2 == event_data_model_json -class TestModel_Expansion(): + +class TestModel_Expansion: """ Test Class for Expansion """ @@ -8499,7 +8877,8 @@ def test_expansion_serialization(self): expansion_model_json2 = expansion_model.to_dict() assert expansion_model_json2 == expansion_model_json -class TestModel_Expansions(): + +class TestModel_Expansions: """ Test Class for Expansions """ @@ -8511,7 +8890,7 @@ def test_expansions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - expansion_model = {} # Expansion + expansion_model = {} # Expansion expansion_model['input_terms'] = ['testString'] expansion_model['expanded_terms'] = ['testString'] @@ -8534,7 +8913,8 @@ def test_expansions_serialization(self): expansions_model_json2 = expansions_model.to_dict() assert expansions_model_json2 == expansions_model_json -class TestModel_Field(): + +class TestModel_Field: """ Test Class for Field """ @@ -8562,7 +8942,8 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestModel_FontSetting(): + +class TestModel_FontSetting: """ Test Class for FontSetting """ @@ -8596,7 +8977,8 @@ def test_font_setting_serialization(self): font_setting_model_json2 = font_setting_model.to_dict() assert font_setting_model_json2 == font_setting_model_json -class TestModel_Gateway(): + +class TestModel_Gateway: """ Test Class for Gateway """ @@ -8629,7 +9011,8 @@ def test_gateway_serialization(self): gateway_model_json2 = gateway_model.to_dict() assert gateway_model_json2 == gateway_model_json -class TestModel_GatewayDelete(): + +class TestModel_GatewayDelete: """ Test Class for GatewayDelete """ @@ -8659,7 +9042,8 @@ def test_gateway_delete_serialization(self): gateway_delete_model_json2 = gateway_delete_model.to_dict() assert gateway_delete_model_json2 == gateway_delete_model_json -class TestModel_GatewayList(): + +class TestModel_GatewayList: """ Test Class for GatewayList """ @@ -8671,7 +9055,7 @@ def test_gateway_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - gateway_model = {} # Gateway + gateway_model = {} # Gateway gateway_model['gateway_id'] = 'testString' gateway_model['name'] = 'testString' gateway_model['status'] = 'connected' @@ -8697,7 +9081,8 @@ def test_gateway_list_serialization(self): gateway_list_model_json2 = gateway_list_model.to_dict() assert gateway_list_model_json2 == gateway_list_model_json -class TestModel_HtmlSettings(): + +class TestModel_HtmlSettings: """ Test Class for HtmlSettings """ @@ -8709,7 +9094,7 @@ def test_html_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] # Construct a json representation of a HtmlSettings model @@ -8736,7 +9121,8 @@ def test_html_settings_serialization(self): html_settings_model_json2 = html_settings_model.to_dict() assert html_settings_model_json2 == html_settings_model_json -class TestModel_IndexCapacity(): + +class TestModel_IndexCapacity: """ Test Class for IndexCapacity """ @@ -8748,11 +9134,11 @@ def test_index_capacity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage # Construct a json representation of a IndexCapacity model index_capacity_model_json = {} @@ -8775,7 +9161,8 @@ def test_index_capacity_serialization(self): index_capacity_model_json2 = index_capacity_model.to_dict() assert index_capacity_model_json2 == index_capacity_model_json -class TestModel_ListCollectionFieldsResponse(): + +class TestModel_ListCollectionFieldsResponse: """ Test Class for ListCollectionFieldsResponse """ @@ -8787,7 +9174,7 @@ def test_list_collection_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - field_model = {} # Field + field_model = {} # Field # Construct a json representation of a ListCollectionFieldsResponse model list_collection_fields_response_model_json = {} @@ -8808,7 +9195,8 @@ def test_list_collection_fields_response_serialization(self): list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json -class TestModel_ListCollectionsResponse(): + +class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse """ @@ -8820,11 +9208,11 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_counts_model = {} # DocumentCounts + document_counts_model = {} # DocumentCounts - collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model = {} # CollectionDiskUsage - training_status_model = {} # TrainingStatus + training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 38 training_status_model['available'] = True training_status_model['processing'] = True @@ -8835,25 +9223,25 @@ def test_list_collections_response_serialization(self): training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'running' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 26 - sdu_status_model = {} # SduStatus + sdu_status_model = {} # SduStatus sdu_status_model['enabled'] = True sdu_status_model['total_annotated_pages'] = 26 sdu_status_model['total_pages'] = 26 sdu_status_model['total_documents'] = 26 sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - collection_model = {} # Collection + collection_model = {} # Collection collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' @@ -8883,7 +9271,8 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestModel_ListConfigurationsResponse(): + +class TestModel_ListConfigurationsResponse: """ Test Class for ListConfigurationsResponse """ @@ -8895,7 +9284,7 @@ def test_list_configurations_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -8903,27 +9292,27 @@ def test_list_configurations_response_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['testString'] html_settings_model['keep_content'] = x_path_patterns_model @@ -8931,17 +9320,17 @@ def test_list_configurations_response_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = False segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'copy' normalization_operation_model['source_field'] = 'testString' normalization_operation_model['destination_field'] = 'testString' - conversions_model = {} # Conversions + conversions_model = {} # Conversions conversions_model['pdf'] = pdf_settings_model conversions_model['word'] = word_settings_model conversions_model['html'] = html_settings_model @@ -8949,12 +9338,12 @@ def test_list_configurations_response_serialization(self): conversions_model['json_normalizations'] = [normalization_operation_model] conversions_model['image_text_recognition'] = True - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8963,41 +9352,41 @@ def test_list_configurations_response_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' - enrichment_model = {} # Enrichment + enrichment_model = {} # Enrichment enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' @@ -9006,39 +9395,39 @@ def test_list_configurations_response_serialization(self): enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -9046,13 +9435,13 @@ def test_list_configurations_response_serialization(self): source_options_model['buckets'] = [source_options_buckets_model] source_options_model['crawl_all_buckets'] = True - source_model = {} # Source + source_model = {} # Source source_model['type'] = 'box' source_model['credential_id'] = 'testString' source_model['schedule'] = source_schedule_model source_model['options'] = source_options_model - configuration_model = {} # Configuration + configuration_model = {} # Configuration configuration_model['name'] = 'testString' configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model @@ -9079,7 +9468,8 @@ def test_list_configurations_response_serialization(self): list_configurations_response_model_json2 = list_configurations_response_model.to_dict() assert list_configurations_response_model_json2 == list_configurations_response_model_json -class TestModel_ListEnvironmentsResponse(): + +class TestModel_ListEnvironmentsResponse: """ Test Class for ListEnvironmentsResponse """ @@ -9091,24 +9481,24 @@ def test_list_environments_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage - index_capacity_model = {} # IndexCapacity + index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model index_capacity_model['disk_usage'] = disk_usage_model index_capacity_model['collections'] = collection_usage_model - search_status_model = {} # SearchStatus + search_status_model = {} # SearchStatus search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' search_status_model['last_trained'] = '2019-01-01' - environment_model = {} # Environment + environment_model = {} # Environment environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' environment_model['size'] = 'LT' @@ -9135,7 +9525,8 @@ def test_list_environments_response_serialization(self): list_environments_response_model_json2 = list_environments_response_model.to_dict() assert list_environments_response_model_json2 == list_environments_response_model_json -class TestModel_LogQueryResponse(): + +class TestModel_LogQueryResponse: """ Test Class for LogQueryResponse """ @@ -9147,18 +9538,18 @@ def test_log_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 log_query_response_result_documents_result_model['confidence'] = 72.5 log_query_response_result_documents_result_model['collection_id'] = 'testString' - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] log_query_response_result_documents_model['count'] = 38 - log_query_response_result_model = {} # LogQueryResponseResult + log_query_response_result_model = {} # LogQueryResponseResult log_query_response_result_model['environment_id'] = 'testString' log_query_response_result_model['customer_id'] = 'testString' log_query_response_result_model['document_type'] = 'query' @@ -9194,7 +9585,8 @@ def test_log_query_response_serialization(self): log_query_response_model_json2 = log_query_response_model.to_dict() assert log_query_response_model_json2 == log_query_response_model_json -class TestModel_LogQueryResponseResult(): + +class TestModel_LogQueryResponseResult: """ Test Class for LogQueryResponseResult """ @@ -9206,14 +9598,14 @@ def test_log_query_response_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 log_query_response_result_documents_result_model['confidence'] = 72.5 log_query_response_result_documents_result_model['collection_id'] = 'testString' - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] log_query_response_result_documents_model['count'] = 38 @@ -9249,7 +9641,8 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json2 = log_query_response_result_model.to_dict() assert log_query_response_result_model_json2 == log_query_response_result_model_json -class TestModel_LogQueryResponseResultDocuments(): + +class TestModel_LogQueryResponseResultDocuments: """ Test Class for LogQueryResponseResultDocuments """ @@ -9261,7 +9654,7 @@ def test_log_query_response_result_documents_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 @@ -9288,7 +9681,8 @@ def test_log_query_response_result_documents_serialization(self): log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json -class TestModel_LogQueryResponseResultDocumentsResult(): + +class TestModel_LogQueryResponseResultDocumentsResult: """ Test Class for LogQueryResponseResultDocumentsResult """ @@ -9321,7 +9715,8 @@ def test_log_query_response_result_documents_result_serialization(self): log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json -class TestModel_MetricAggregation(): + +class TestModel_MetricAggregation: """ Test Class for MetricAggregation """ @@ -9333,7 +9728,7 @@ def test_metric_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model = {} # MetricAggregationResult metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 @@ -9360,7 +9755,8 @@ def test_metric_aggregation_serialization(self): metric_aggregation_model_json2 = metric_aggregation_model.to_dict() assert metric_aggregation_model_json2 == metric_aggregation_model_json -class TestModel_MetricAggregationResult(): + +class TestModel_MetricAggregationResult: """ Test Class for MetricAggregationResult """ @@ -9392,7 +9788,8 @@ def test_metric_aggregation_result_serialization(self): metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json -class TestModel_MetricResponse(): + +class TestModel_MetricResponse: """ Test Class for MetricResponse """ @@ -9404,13 +9801,13 @@ def test_metric_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model = {} # MetricAggregationResult metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 - metric_aggregation_model = {} # MetricAggregation + metric_aggregation_model = {} # MetricAggregation metric_aggregation_model['interval'] = 'testString' metric_aggregation_model['event_type'] = 'testString' metric_aggregation_model['results'] = [metric_aggregation_result_model] @@ -9434,7 +9831,8 @@ def test_metric_response_serialization(self): metric_response_model_json2 = metric_response_model.to_dict() assert metric_response_model_json2 == metric_response_model_json -class TestModel_MetricTokenAggregation(): + +class TestModel_MetricTokenAggregation: """ Test Class for MetricTokenAggregation """ @@ -9446,7 +9844,7 @@ def test_metric_token_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult metric_token_aggregation_result_model['key'] = 'testString' metric_token_aggregation_result_model['matching_results'] = 38 metric_token_aggregation_result_model['event_rate'] = 72.5 @@ -9471,7 +9869,8 @@ def test_metric_token_aggregation_serialization(self): metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json -class TestModel_MetricTokenAggregationResult(): + +class TestModel_MetricTokenAggregationResult: """ Test Class for MetricTokenAggregationResult """ @@ -9502,7 +9901,8 @@ def test_metric_token_aggregation_result_serialization(self): metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json -class TestModel_MetricTokenResponse(): + +class TestModel_MetricTokenResponse: """ Test Class for MetricTokenResponse """ @@ -9514,12 +9914,12 @@ def test_metric_token_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult metric_token_aggregation_result_model['key'] = 'testString' metric_token_aggregation_result_model['matching_results'] = 38 metric_token_aggregation_result_model['event_rate'] = 72.5 - metric_token_aggregation_model = {} # MetricTokenAggregation + metric_token_aggregation_model = {} # MetricTokenAggregation metric_token_aggregation_model['event_type'] = 'testString' metric_token_aggregation_model['results'] = [metric_token_aggregation_result_model] @@ -9542,7 +9942,8 @@ def test_metric_token_response_serialization(self): metric_token_response_model_json2 = metric_token_response_model.to_dict() assert metric_token_response_model_json2 == metric_token_response_model_json -class TestModel_NluEnrichmentConcepts(): + +class TestModel_NluEnrichmentConcepts: """ Test Class for NluEnrichmentConcepts """ @@ -9571,7 +9972,8 @@ def test_nlu_enrichment_concepts_serialization(self): nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json -class TestModel_NluEnrichmentEmotion(): + +class TestModel_NluEnrichmentEmotion: """ Test Class for NluEnrichmentEmotion """ @@ -9601,7 +10003,8 @@ def test_nlu_enrichment_emotion_serialization(self): nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json -class TestModel_NluEnrichmentEntities(): + +class TestModel_NluEnrichmentEntities: """ Test Class for NluEnrichmentEntities """ @@ -9636,7 +10039,8 @@ def test_nlu_enrichment_entities_serialization(self): nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json -class TestModel_NluEnrichmentFeatures(): + +class TestModel_NluEnrichmentFeatures: """ Test Class for NluEnrichmentFeatures """ @@ -9648,12 +10052,12 @@ def test_nlu_enrichment_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -9662,23 +10066,23 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 # Construct a json representation of a NluEnrichmentFeatures model @@ -9687,7 +10091,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model_json['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model @@ -9707,7 +10111,8 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json -class TestModel_NluEnrichmentKeywords(): + +class TestModel_NluEnrichmentKeywords: """ Test Class for NluEnrichmentKeywords """ @@ -9738,7 +10143,8 @@ def test_nlu_enrichment_keywords_serialization(self): nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json -class TestModel_NluEnrichmentRelations(): + +class TestModel_NluEnrichmentRelations: """ Test Class for NluEnrichmentRelations """ @@ -9767,7 +10173,8 @@ def test_nlu_enrichment_relations_serialization(self): nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json -class TestModel_NluEnrichmentSemanticRoles(): + +class TestModel_NluEnrichmentSemanticRoles: """ Test Class for NluEnrichmentSemanticRoles """ @@ -9798,7 +10205,8 @@ def test_nlu_enrichment_semantic_roles_serialization(self): nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json -class TestModel_NluEnrichmentSentiment(): + +class TestModel_NluEnrichmentSentiment: """ Test Class for NluEnrichmentSentiment """ @@ -9828,7 +10236,8 @@ def test_nlu_enrichment_sentiment_serialization(self): nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json -class TestModel_NormalizationOperation(): + +class TestModel_NormalizationOperation: """ Test Class for NormalizationOperation """ @@ -9859,7 +10268,8 @@ def test_normalization_operation_serialization(self): normalization_operation_model_json2 = normalization_operation_model.to_dict() assert normalization_operation_model_json2 == normalization_operation_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -9887,7 +10297,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_PdfHeadingDetection(): + +class TestModel_PdfHeadingDetection: """ Test Class for PdfHeadingDetection """ @@ -9899,7 +10310,7 @@ def test_pdf_heading_detection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -9926,7 +10337,8 @@ def test_pdf_heading_detection_serialization(self): pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json -class TestModel_PdfSettings(): + +class TestModel_PdfSettings: """ Test Class for PdfSettings """ @@ -9938,7 +10350,7 @@ def test_pdf_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -9946,7 +10358,7 @@ def test_pdf_settings_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] # Construct a json representation of a PdfSettings model @@ -9968,7 +10380,8 @@ def test_pdf_settings_serialization(self): pdf_settings_model_json2 = pdf_settings_model.to_dict() assert pdf_settings_model_json2 == pdf_settings_model_json -class TestModel_QueryAggregation(): + +class TestModel_QueryAggregation: """ Test Class for QueryAggregation """ @@ -9997,7 +10410,8 @@ def test_query_aggregation_serialization(self): query_aggregation_model_json2 = query_aggregation_model.to_dict() assert query_aggregation_model_json2 == query_aggregation_model_json -class TestModel_QueryHistogramAggregationResult(): + +class TestModel_QueryHistogramAggregationResult: """ Test Class for QueryHistogramAggregationResult """ @@ -10009,7 +10423,7 @@ def test_query_histogram_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10035,7 +10449,8 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json -class TestModel_QueryNoticesResponse(): + +class TestModel_QueryNoticesResponse: """ Test Class for QueryNoticesResponse """ @@ -10047,15 +10462,15 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - notice_model = {} # Notice + notice_model = {} # Notice - query_notices_result_model = {} # QueryNoticesResult + query_notices_result_model = {} # QueryNoticesResult query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {'foo': 'bar'} + query_notices_result_model['metadata'] = {'anyKey': 'anyValue'} query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' query_notices_result_model['result_metadata'] = query_result_metadata_model query_notices_result_model['code'] = 200 @@ -10065,12 +10480,12 @@ def test_query_notices_response_serialization(self): query_notices_result_model['notices'] = [notice_model] query_notices_result_model['score'] = '1' - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 - query_passages_model = {} # QueryPassages + query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' query_passages_model['passage_score'] = 72.5 query_passages_model['passage_text'] = 'testString' @@ -10101,7 +10516,8 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestModel_QueryNoticesResult(): + +class TestModel_QueryNoticesResult: """ Test Class for QueryNoticesResult """ @@ -10113,16 +10529,16 @@ def test_query_notices_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a QueryNoticesResult model query_notices_result_model_json = {} query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {'foo': 'bar'} + query_notices_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_notices_result_model_json['collection_id'] = 'testString' query_notices_result_model_json['result_metadata'] = query_result_metadata_model query_notices_result_model_json['code'] = 38 @@ -10157,7 +10573,8 @@ def test_query_notices_result_serialization(self): actual_dict = query_notices_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryPassages(): + +class TestModel_QueryPassages: """ Test Class for QueryPassages """ @@ -10191,7 +10608,8 @@ def test_query_passages_serialization(self): query_passages_model_json2 = query_passages_model.to_dict() assert query_passages_model_json2 == query_passages_model_json -class TestModel_QueryResponse(): + +class TestModel_QueryResponse: """ Test Class for QueryResponse """ @@ -10203,23 +10621,23 @@ def test_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - query_result_model = {} # QueryResult + query_result_model = {} # QueryResult query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {'foo': 'bar'} + query_result_model['metadata'] = {'anyKey': 'anyValue'} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model query_result_model['score'] = '1' - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 - query_passages_model = {} # QueryPassages + query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' query_passages_model['passage_score'] = 72.5 query_passages_model['passage_text'] = 'testString' @@ -10227,7 +10645,7 @@ def test_query_response_serialization(self): query_passages_model['end_offset'] = 38 query_passages_model['field'] = 'testString' - retrieval_details_model = {} # RetrievalDetails + retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' # Construct a json representation of a QueryResponse model @@ -10256,7 +10674,8 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestModel_QueryResult(): + +class TestModel_QueryResult: """ Test Class for QueryResult """ @@ -10268,14 +10687,14 @@ def test_query_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {'foo': 'bar'} + query_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_result_model_json['collection_id'] = 'testString' query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['foo'] = 'testString' @@ -10305,7 +10724,8 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryResultMetadata(): + +class TestModel_QueryResultMetadata: """ Test Class for QueryResultMetadata """ @@ -10335,7 +10755,8 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestModel_QueryTermAggregationResult(): + +class TestModel_QueryTermAggregationResult: """ Test Class for QueryTermAggregationResult """ @@ -10347,7 +10768,7 @@ def test_query_term_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10376,7 +10797,8 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json -class TestModel_QueryTimesliceAggregationResult(): + +class TestModel_QueryTimesliceAggregationResult: """ Test Class for QueryTimesliceAggregationResult """ @@ -10388,7 +10810,7 @@ def test_query_timeslice_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10415,7 +10837,8 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json -class TestModel_QueryTopHitsAggregationResult(): + +class TestModel_QueryTopHitsAggregationResult: """ Test Class for QueryTopHitsAggregationResult """ @@ -10428,7 +10851,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -10445,7 +10868,8 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json -class TestModel_RetrievalDetails(): + +class TestModel_RetrievalDetails: """ Test Class for RetrievalDetails """ @@ -10474,7 +10898,8 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestModel_SduStatus(): + +class TestModel_SduStatus: """ Test Class for SduStatus """ @@ -10486,7 +10911,7 @@ def test_sdu_status_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 26 @@ -10513,7 +10938,8 @@ def test_sdu_status_serialization(self): sdu_status_model_json2 = sdu_status_model.to_dict() assert sdu_status_model_json2 == sdu_status_model_json -class TestModel_SduStatusCustomFields(): + +class TestModel_SduStatusCustomFields: """ Test Class for SduStatusCustomFields """ @@ -10543,7 +10969,8 @@ def test_sdu_status_custom_fields_serialization(self): sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json -class TestModel_SearchStatus(): + +class TestModel_SearchStatus: """ Test Class for SearchStatus """ @@ -10575,7 +11002,8 @@ def test_search_status_serialization(self): search_status_model_json2 = search_status_model.to_dict() assert search_status_model_json2 == search_status_model_json -class TestModel_SegmentSettings(): + +class TestModel_SegmentSettings: """ Test Class for SegmentSettings """ @@ -10606,7 +11034,8 @@ def test_segment_settings_serialization(self): segment_settings_model_json2 = segment_settings_model.to_dict() assert segment_settings_model_json2 == segment_settings_model_json -class TestModel_Source(): + +class TestModel_Source: """ Test Class for Source """ @@ -10618,39 +11047,39 @@ def test_source_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -10680,7 +11109,8 @@ def test_source_serialization(self): source_model_json2 = source_model.to_dict() assert source_model_json2 == source_model_json -class TestModel_SourceOptions(): + +class TestModel_SourceOptions: """ Test Class for SourceOptions """ @@ -10692,30 +11122,30 @@ def test_source_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 @@ -10743,7 +11173,8 @@ def test_source_options_serialization(self): source_options_model_json2 = source_options_model.to_dict() assert source_options_model_json2 == source_options_model_json -class TestModel_SourceOptionsBuckets(): + +class TestModel_SourceOptionsBuckets: """ Test Class for SourceOptionsBuckets """ @@ -10773,7 +11204,8 @@ def test_source_options_buckets_serialization(self): source_options_buckets_model_json2 = source_options_buckets_model.to_dict() assert source_options_buckets_model_json2 == source_options_buckets_model_json -class TestModel_SourceOptionsFolder(): + +class TestModel_SourceOptionsFolder: """ Test Class for SourceOptionsFolder """ @@ -10804,7 +11236,8 @@ def test_source_options_folder_serialization(self): source_options_folder_model_json2 = source_options_folder_model.to_dict() assert source_options_folder_model_json2 == source_options_folder_model_json -class TestModel_SourceOptionsObject(): + +class TestModel_SourceOptionsObject: """ Test Class for SourceOptionsObject """ @@ -10834,7 +11267,8 @@ def test_source_options_object_serialization(self): source_options_object_model_json2 = source_options_object_model.to_dict() assert source_options_object_model_json2 == source_options_object_model_json -class TestModel_SourceOptionsSiteColl(): + +class TestModel_SourceOptionsSiteColl: """ Test Class for SourceOptionsSiteColl """ @@ -10864,7 +11298,8 @@ def test_source_options_site_coll_serialization(self): source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() assert source_options_site_coll_model_json2 == source_options_site_coll_model_json -class TestModel_SourceOptionsWebCrawl(): + +class TestModel_SourceOptionsWebCrawl: """ Test Class for SourceOptionsWebCrawl """ @@ -10880,8 +11315,8 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json['limit_to_starting_hosts'] = True source_options_web_crawl_model_json['crawl_speed'] = 'normal' source_options_web_crawl_model_json['allow_untrusted_certificate'] = False - source_options_web_crawl_model_json['maximum_hops'] = 38 - source_options_web_crawl_model_json['request_timeout'] = 38 + source_options_web_crawl_model_json['maximum_hops'] = 2 + source_options_web_crawl_model_json['request_timeout'] = 30000 source_options_web_crawl_model_json['override_robots_txt'] = False source_options_web_crawl_model_json['blacklist'] = ['testString'] @@ -10900,7 +11335,8 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json -class TestModel_SourceSchedule(): + +class TestModel_SourceSchedule: """ Test Class for SourceSchedule """ @@ -10931,7 +11367,8 @@ def test_source_schedule_serialization(self): source_schedule_model_json2 = source_schedule_model.to_dict() assert source_schedule_model_json2 == source_schedule_model_json -class TestModel_SourceStatus(): + +class TestModel_SourceStatus: """ Test Class for SourceStatus """ @@ -10961,7 +11398,8 @@ def test_source_status_serialization(self): source_status_model_json2 = source_status_model.to_dict() assert source_status_model_json2 == source_status_model_json -class TestModel_StatusDetails(): + +class TestModel_StatusDetails: """ Test Class for StatusDetails """ @@ -10991,7 +11429,8 @@ def test_status_details_serialization(self): status_details_model_json2 = status_details_model.to_dict() assert status_details_model_json2 == status_details_model_json -class TestModel_TokenDictRule(): + +class TestModel_TokenDictRule: """ Test Class for TokenDictRule """ @@ -11023,7 +11462,8 @@ def test_token_dict_rule_serialization(self): token_dict_rule_model_json2 = token_dict_rule_model.to_dict() assert token_dict_rule_model_json2 == token_dict_rule_model_json -class TestModel_TokenDictStatusResponse(): + +class TestModel_TokenDictStatusResponse: """ Test Class for TokenDictStatusResponse """ @@ -11053,7 +11493,8 @@ def test_token_dict_status_response_serialization(self): token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() assert token_dict_status_response_model_json2 == token_dict_status_response_model_json -class TestModel_TrainingDataSet(): + +class TestModel_TrainingDataSet: """ Test Class for TrainingDataSet """ @@ -11065,12 +11506,12 @@ def test_training_data_set_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 - training_query_model = {} # TrainingQuery + training_query_model = {} # TrainingQuery training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' @@ -11097,7 +11538,8 @@ def test_training_data_set_serialization(self): training_data_set_model_json2 = training_data_set_model.to_dict() assert training_data_set_model_json2 == training_data_set_model_json -class TestModel_TrainingExample(): + +class TestModel_TrainingExample: """ Test Class for TrainingExample """ @@ -11128,7 +11570,8 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestModel_TrainingExampleList(): + +class TestModel_TrainingExampleList: """ Test Class for TrainingExampleList """ @@ -11140,7 +11583,7 @@ def test_training_example_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 @@ -11164,7 +11607,8 @@ def test_training_example_list_serialization(self): training_example_list_model_json2 = training_example_list_model.to_dict() assert training_example_list_model_json2 == training_example_list_model_json -class TestModel_TrainingQuery(): + +class TestModel_TrainingQuery: """ Test Class for TrainingQuery """ @@ -11176,7 +11620,7 @@ def test_training_query_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 @@ -11203,7 +11647,8 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestModel_TrainingStatus(): + +class TestModel_TrainingStatus: """ Test Class for TrainingStatus """ @@ -11240,7 +11685,8 @@ def test_training_status_serialization(self): training_status_model_json2 = training_status_model.to_dict() assert training_status_model_json2 == training_status_model_json -class TestModel_WordHeadingDetection(): + +class TestModel_WordHeadingDetection: """ Test Class for WordHeadingDetection """ @@ -11252,7 +11698,7 @@ def test_word_heading_detection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -11260,7 +11706,7 @@ def test_word_heading_detection_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] @@ -11284,7 +11730,8 @@ def test_word_heading_detection_serialization(self): word_heading_detection_model_json2 = word_heading_detection_model.to_dict() assert word_heading_detection_model_json2 == word_heading_detection_model_json -class TestModel_WordSettings(): + +class TestModel_WordSettings: """ Test Class for WordSettings """ @@ -11296,7 +11743,7 @@ def test_word_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -11304,11 +11751,11 @@ def test_word_settings_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] @@ -11331,7 +11778,8 @@ def test_word_settings_serialization(self): word_settings_model_json2 = word_settings_model.to_dict() assert word_settings_model_json2 == word_settings_model_json -class TestModel_WordStyle(): + +class TestModel_WordStyle: """ Test Class for WordStyle """ @@ -11361,7 +11809,8 @@ def test_word_style_serialization(self): word_style_model_json2 = word_style_model.to_dict() assert word_style_model_json2 == word_style_model_json -class TestModel_XPathPatterns(): + +class TestModel_XPathPatterns: """ Test Class for XPathPatterns """ @@ -11390,7 +11839,8 @@ def test_x_path_patterns_serialization(self): x_path_patterns_model_json2 = x_path_patterns_model.to_dict() assert x_path_patterns_model_json2 == x_path_patterns_model_json -class TestModel_QueryCalculationAggregation(): + +class TestModel_QueryCalculationAggregation: """ Test Class for QueryCalculationAggregation """ @@ -11421,7 +11871,8 @@ def test_query_calculation_aggregation_serialization(self): query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json -class TestModel_QueryFilterAggregation(): + +class TestModel_QueryFilterAggregation: """ Test Class for QueryFilterAggregation """ @@ -11452,7 +11903,8 @@ def test_query_filter_aggregation_serialization(self): query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json -class TestModel_QueryHistogramAggregation(): + +class TestModel_QueryHistogramAggregation: """ Test Class for QueryHistogramAggregation """ @@ -11484,7 +11936,8 @@ def test_query_histogram_aggregation_serialization(self): query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json -class TestModel_QueryNestedAggregation(): + +class TestModel_QueryNestedAggregation: """ Test Class for QueryNestedAggregation """ @@ -11515,7 +11968,8 @@ def test_query_nested_aggregation_serialization(self): query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json -class TestModel_QueryTermAggregation(): + +class TestModel_QueryTermAggregation: """ Test Class for QueryTermAggregation """ @@ -11547,7 +12001,8 @@ def test_query_term_aggregation_serialization(self): query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() assert query_term_aggregation_model_json2 == query_term_aggregation_model_json -class TestModel_QueryTimesliceAggregation(): + +class TestModel_QueryTimesliceAggregation: """ Test Class for QueryTimesliceAggregation """ @@ -11579,7 +12034,8 @@ def test_query_timeslice_aggregation_serialization(self): query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json -class TestModel_QueryTopHitsAggregation(): + +class TestModel_QueryTopHitsAggregation: """ Test Class for QueryTopHitsAggregation """ @@ -11591,9 +12047,9 @@ def test_query_top_hits_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 08c84b14..3b1008aa 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListProjects(): + +class TestListProjects: """ Test Class for list_projects """ @@ -86,16 +86,17 @@ def test_list_projects_all_params(self): # Set up mock url = preprocess_url('/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_projects() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -117,17 +118,19 @@ def test_list_projects_value_error(self): # Set up mock url = preprocess_url('/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_projects(**req_copy) @@ -140,7 +143,8 @@ def test_list_projects_value_error_with_retries(self): _service.disable_retries() self.test_list_projects_value_error() -class TestCreateProject(): + +class TestCreateProject: """ Test Class for create_project """ @@ -152,12 +156,14 @@ def test_create_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DefaultQueryParamsPassages model default_query_params_passages_model = {} @@ -172,7 +178,7 @@ def test_create_project_all_params(self): default_query_params_table_results_model = {} default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model default_query_params_suggested_refinements_model = {} @@ -202,7 +208,7 @@ def test_create_project_all_params(self): name, type, default_query_parameters=default_query_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -230,12 +236,14 @@ def test_create_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DefaultQueryParamsPassages model default_query_params_passages_model = {} @@ -250,7 +258,7 @@ def test_create_project_value_error(self): default_query_params_table_results_model = {} default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model default_query_params_suggested_refinements_model = {} @@ -281,7 +289,7 @@ def test_create_project_value_error(self): "type": type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_project(**req_copy) @@ -294,7 +302,8 @@ def test_create_project_value_error_with_retries(self): _service.disable_retries() self.test_create_project_value_error() -class TestGetProject(): + +class TestGetProject: """ Test Class for get_project """ @@ -306,12 +315,14 @@ def test_get_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -319,7 +330,7 @@ def test_get_project_all_params(self): # Invoke method response = _service.get_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -342,12 +353,14 @@ def test_get_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -357,7 +370,7 @@ def test_get_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_project(**req_copy) @@ -370,7 +383,8 @@ def test_get_project_value_error_with_retries(self): _service.disable_retries() self.test_get_project_value_error() -class TestUpdateProject(): + +class TestUpdateProject: """ Test Class for update_project """ @@ -382,12 +396,14 @@ def test_update_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -397,7 +413,7 @@ def test_update_project_all_params(self): response = _service.update_project( project_id, name=name, - headers={} + headers={}, ) # Check for correct operation @@ -423,12 +439,14 @@ def test_update_project_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -436,7 +454,7 @@ def test_update_project_required_params(self): # Invoke method response = _service.update_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -459,12 +477,14 @@ def test_update_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -474,7 +494,7 @@ def test_update_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_project(**req_copy) @@ -487,7 +507,8 @@ def test_update_project_value_error_with_retries(self): _service.disable_retries() self.test_update_project_value_error() -class TestDeleteProject(): + +class TestDeleteProject: """ Test Class for delete_project """ @@ -499,9 +520,11 @@ def test_delete_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -509,7 +532,7 @@ def test_delete_project_all_params(self): # Invoke method response = _service.delete_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -532,9 +555,11 @@ def test_delete_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -544,7 +569,7 @@ def test_delete_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_project(**req_copy) @@ -557,7 +582,8 @@ def test_delete_project_value_error_with_retries(self): _service.disable_retries() self.test_delete_project_value_error() -class TestListFields(): + +class TestListFields: """ Test Class for list_fields """ @@ -570,11 +596,13 @@ def test_list_fields_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -584,14 +612,14 @@ def test_list_fields_all_params(self): response = _service.list_fields( project_id, collection_ids=collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -612,11 +640,13 @@ def test_list_fields_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -624,7 +654,7 @@ def test_list_fields_required_params(self): # Invoke method response = _service.list_fields( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -648,11 +678,13 @@ def test_list_fields_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -662,7 +694,7 @@ def test_list_fields_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_fields(**req_copy) @@ -675,6 +707,7 @@ def test_list_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_fields_value_error() + # endregion ############################################################################## # End of Service: Projects @@ -685,7 +718,8 @@ def test_list_fields_value_error_with_retries(self): ############################################################################## # region -class TestListCollections(): + +class TestListCollections: """ Test Class for list_collections """ @@ -698,11 +732,13 @@ def test_list_collections_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -710,7 +746,7 @@ def test_list_collections_all_params(self): # Invoke method response = _service.list_collections( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -734,11 +770,13 @@ def test_list_collections_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -748,7 +786,7 @@ def test_list_collections_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collections(**req_copy) @@ -761,7 +799,8 @@ def test_list_collections_value_error_with_retries(self): _service.disable_retries() self.test_list_collections_value_error() -class TestCreateCollection(): + +class TestCreateCollection: """ Test Class for create_collection """ @@ -774,11 +813,13 @@ def test_create_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -799,7 +840,7 @@ def test_create_collection_all_params(self): description=description, language=language, enrichments=enrichments, - headers={} + headers={}, ) # Check for correct operation @@ -829,11 +870,13 @@ def test_create_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -853,7 +896,7 @@ def test_create_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_collection(**req_copy) @@ -866,7 +909,8 @@ def test_create_collection_value_error_with_retries(self): _service.disable_retries() self.test_create_collection_value_error() -class TestGetCollection(): + +class TestGetCollection: """ Test Class for get_collection """ @@ -879,11 +923,13 @@ def test_get_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -893,7 +939,7 @@ def test_get_collection_all_params(self): response = _service.get_collection( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -917,11 +963,13 @@ def test_get_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -933,7 +981,7 @@ def test_get_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_collection(**req_copy) @@ -946,7 +994,8 @@ def test_get_collection_value_error_with_retries(self): _service.disable_retries() self.test_get_collection_value_error() -class TestUpdateCollection(): + +class TestUpdateCollection: """ Test Class for update_collection """ @@ -959,11 +1008,13 @@ def test_update_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -984,7 +1035,7 @@ def test_update_collection_all_params(self): name=name, description=description, enrichments=enrichments, - headers={} + headers={}, ) # Check for correct operation @@ -1013,11 +1064,13 @@ def test_update_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -1037,7 +1090,7 @@ def test_update_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_collection(**req_copy) @@ -1050,7 +1103,8 @@ def test_update_collection_value_error_with_retries(self): _service.disable_retries() self.test_update_collection_value_error() -class TestDeleteCollection(): + +class TestDeleteCollection: """ Test Class for delete_collection """ @@ -1062,9 +1116,11 @@ def test_delete_collection_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -1074,7 +1130,7 @@ def test_delete_collection_all_params(self): response = _service.delete_collection( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1097,9 +1153,11 @@ def test_delete_collection_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -1111,7 +1169,7 @@ def test_delete_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_collection(**req_copy) @@ -1124,6 +1182,7 @@ def test_delete_collection_value_error_with_retries(self): _service.disable_retries() self.test_delete_collection_value_error() + # endregion ############################################################################## # End of Service: Collections @@ -1134,7 +1193,8 @@ def test_delete_collection_value_error_with_retries(self): ############################################################################## # region -class TestListDocuments(): + +class TestListDocuments: """ Test Class for list_documents """ @@ -1147,16 +1207,18 @@ def test_list_documents_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' collection_id = 'testString' - count = 38 + count = 1000 status = 'testString' has_notices = True is_parent = True @@ -1173,14 +1235,14 @@ def test_list_documents_all_params(self): is_parent=is_parent, parent_document_id=parent_document_id, sha256=sha256, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string assert 'status={}'.format(status) in query_string @@ -1206,11 +1268,13 @@ def test_list_documents_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1220,7 +1284,7 @@ def test_list_documents_required_params(self): response = _service.list_documents( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1244,11 +1308,13 @@ def test_list_documents_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1260,7 +1326,7 @@ def test_list_documents_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_documents(**req_copy) @@ -1273,7 +1339,8 @@ def test_list_documents_value_error_with_retries(self): _service.disable_retries() self.test_list_documents_value_error() -class TestAddDocument(): + +class TestAddDocument: """ Test Class for add_document """ @@ -1286,11 +1353,13 @@ def test_add_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1310,7 +1379,7 @@ def test_add_document_all_params(self): file_content_type=file_content_type, metadata=metadata, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1334,11 +1403,13 @@ def test_add_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1348,7 +1419,7 @@ def test_add_document_required_params(self): response = _service.add_document( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1372,11 +1443,13 @@ def test_add_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1388,7 +1461,7 @@ def test_add_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_document(**req_copy) @@ -1401,7 +1474,8 @@ def test_add_document_value_error_with_retries(self): _service.disable_retries() self.test_add_document_value_error() -class TestGetDocument(): + +class TestGetDocument: """ Test Class for get_document """ @@ -1414,11 +1488,13 @@ def test_get_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1430,7 +1506,7 @@ def test_get_document_all_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1454,11 +1530,13 @@ def test_get_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1472,7 +1550,7 @@ def test_get_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document(**req_copy) @@ -1485,7 +1563,8 @@ def test_get_document_value_error_with_retries(self): _service.disable_retries() self.test_get_document_value_error() -class TestUpdateDocument(): + +class TestUpdateDocument: """ Test Class for update_document """ @@ -1498,11 +1577,13 @@ def test_update_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1524,7 +1605,7 @@ def test_update_document_all_params(self): file_content_type=file_content_type, metadata=metadata, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1548,11 +1629,13 @@ def test_update_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1564,7 +1647,7 @@ def test_update_document_required_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1588,11 +1671,13 @@ def test_update_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1606,7 +1691,7 @@ def test_update_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document(**req_copy) @@ -1619,7 +1704,8 @@ def test_update_document_value_error_with_retries(self): _service.disable_retries() self.test_update_document_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -1632,11 +1718,13 @@ def test_delete_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1650,7 +1738,7 @@ def test_delete_document_all_params(self): collection_id, document_id, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1674,11 +1762,13 @@ def test_delete_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1690,7 +1780,7 @@ def test_delete_document_required_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1714,11 +1804,13 @@ def test_delete_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1732,7 +1824,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -1745,6 +1837,7 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() + # endregion ############################################################################## # End of Service: Documents @@ -1755,7 +1848,8 @@ def test_delete_document_value_error_with_retries(self): ############################################################################## # region -class TestQuery(): + +class TestQuery: """ Test Class for query """ @@ -1767,12 +1861,14 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a QueryLargeTableResults model query_large_table_results_model = {} @@ -1793,7 +1889,7 @@ def test_query_all_params(self): query_large_passages_model['count'] = 400 query_large_passages_model['characters'] = 50 query_large_passages_model['find_answers'] = False - query_large_passages_model['max_answers_per_passage'] = 38 + query_large_passages_model['max_answers_per_passage'] = 1 # Construct a dict representation of a QueryLargeSimilar model query_large_similar_model = {} @@ -1837,7 +1933,7 @@ def test_query_all_params(self): suggested_refinements=suggested_refinements, passages=passages, similar=similar, - headers={} + headers={}, ) # Check for correct operation @@ -1877,12 +1973,14 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1890,7 +1988,7 @@ def test_query_required_params(self): # Invoke method response = _service.query( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -1913,12 +2011,14 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1928,7 +2028,7 @@ def test_query_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query(**req_copy) @@ -1941,7 +2041,8 @@ def test_query_value_error_with_retries(self): _service.disable_retries() self.test_query_value_error() -class TestGetAutocompletion(): + +class TestGetAutocompletion: """ Test Class for get_autocompletion """ @@ -1954,18 +2055,20 @@ def test_get_autocompletion_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' prefix = 'testString' collection_ids = ['testString'] field = 'testString' - count = 38 + count = 5 # Invoke method response = _service.get_autocompletion( @@ -1974,14 +2077,14 @@ def test_get_autocompletion_all_params(self): collection_ids=collection_ids, field=field, count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -2005,11 +2108,13 @@ def test_get_autocompletion_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2019,14 +2124,14 @@ def test_get_autocompletion_required_params(self): response = _service.get_autocompletion( project_id, prefix, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string @@ -2047,11 +2152,13 @@ def test_get_autocompletion_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2063,7 +2170,7 @@ def test_get_autocompletion_value_error(self): "prefix": prefix, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) @@ -2076,7 +2183,8 @@ def test_get_autocompletion_value_error_with_retries(self): _service.disable_retries() self.test_get_autocompletion_value_error() -class TestQueryCollectionNotices(): + +class TestQueryCollectionNotices: """ Test Class for query_collection_notices """ @@ -2089,11 +2197,13 @@ def test_query_collection_notices_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2101,7 +2211,7 @@ def test_query_collection_notices_all_params(self): filter = 'testString' query = 'testString' natural_language_query = 'testString' - count = 38 + count = 10 offset = 38 # Invoke method @@ -2113,14 +2223,14 @@ def test_query_collection_notices_all_params(self): natural_language_query=natural_language_query, count=count, offset=offset, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -2145,11 +2255,13 @@ def test_query_collection_notices_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2159,7 +2271,7 @@ def test_query_collection_notices_required_params(self): response = _service.query_collection_notices( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2183,11 +2295,13 @@ def test_query_collection_notices_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2199,7 +2313,7 @@ def test_query_collection_notices_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_collection_notices(**req_copy) @@ -2212,7 +2326,8 @@ def test_query_collection_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_collection_notices_value_error() -class TestQueryNotices(): + +class TestQueryNotices: """ Test Class for query_notices """ @@ -2225,18 +2340,20 @@ def test_query_notices_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' filter = 'testString' query = 'testString' natural_language_query = 'testString' - count = 38 + count = 10 offset = 38 # Invoke method @@ -2247,14 +2364,14 @@ def test_query_notices_all_params(self): natural_language_query=natural_language_query, count=count, offset=offset, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -2279,11 +2396,13 @@ def test_query_notices_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2291,7 +2410,7 @@ def test_query_notices_required_params(self): # Invoke method response = _service.query_notices( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -2315,11 +2434,13 @@ def test_query_notices_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2329,7 +2450,7 @@ def test_query_notices_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_notices(**req_copy) @@ -2342,6 +2463,7 @@ def test_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_notices_value_error() + # endregion ############################################################################## # End of Service: Queries @@ -2352,7 +2474,8 @@ def test_query_notices_value_error_with_retries(self): ############################################################################## # region -class TestGetStopwordList(): + +class TestGetStopwordList: """ Test Class for get_stopword_list """ @@ -2365,11 +2488,13 @@ def test_get_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2379,7 +2504,7 @@ def test_get_stopword_list_all_params(self): response = _service.get_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2403,11 +2528,13 @@ def test_get_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2419,7 +2546,7 @@ def test_get_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_stopword_list(**req_copy) @@ -2432,7 +2559,8 @@ def test_get_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_get_stopword_list_value_error() -class TestCreateStopwordList(): + +class TestCreateStopwordList: """ Test Class for create_stopword_list """ @@ -2445,11 +2573,13 @@ def test_create_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2461,7 +2591,7 @@ def test_create_stopword_list_all_params(self): project_id, collection_id, stopwords=stopwords, - headers={} + headers={}, ) # Check for correct operation @@ -2488,11 +2618,13 @@ def test_create_stopword_list_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2502,7 +2634,7 @@ def test_create_stopword_list_required_params(self): response = _service.create_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2526,11 +2658,13 @@ def test_create_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2542,7 +2676,7 @@ def test_create_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) @@ -2555,7 +2689,8 @@ def test_create_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_create_stopword_list_value_error() -class TestDeleteStopwordList(): + +class TestDeleteStopwordList: """ Test Class for delete_stopword_list """ @@ -2567,9 +2702,11 @@ def test_delete_stopword_list_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2579,7 +2716,7 @@ def test_delete_stopword_list_all_params(self): response = _service.delete_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2602,9 +2739,11 @@ def test_delete_stopword_list_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2616,7 +2755,7 @@ def test_delete_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) @@ -2629,7 +2768,8 @@ def test_delete_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_delete_stopword_list_value_error() -class TestListExpansions(): + +class TestListExpansions: """ Test Class for list_expansions """ @@ -2642,11 +2782,13 @@ def test_list_expansions_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2656,7 +2798,7 @@ def test_list_expansions_all_params(self): response = _service.list_expansions( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2680,11 +2822,13 @@ def test_list_expansions_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2696,7 +2840,7 @@ def test_list_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_expansions(**req_copy) @@ -2709,7 +2853,8 @@ def test_list_expansions_value_error_with_retries(self): _service.disable_retries() self.test_list_expansions_value_error() -class TestCreateExpansions(): + +class TestCreateExpansions: """ Test Class for create_expansions """ @@ -2722,11 +2867,13 @@ def test_create_expansions_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2743,7 +2890,7 @@ def test_create_expansions_all_params(self): project_id, collection_id, expansions, - headers={} + headers={}, ) # Check for correct operation @@ -2770,11 +2917,13 @@ def test_create_expansions_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2793,7 +2942,7 @@ def test_create_expansions_value_error(self): "expansions": expansions, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_expansions(**req_copy) @@ -2806,7 +2955,8 @@ def test_create_expansions_value_error_with_retries(self): _service.disable_retries() self.test_create_expansions_value_error() -class TestDeleteExpansions(): + +class TestDeleteExpansions: """ Test Class for delete_expansions """ @@ -2818,9 +2968,11 @@ def test_delete_expansions_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2830,7 +2982,7 @@ def test_delete_expansions_all_params(self): response = _service.delete_expansions( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2853,9 +3005,11 @@ def test_delete_expansions_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2867,7 +3021,7 @@ def test_delete_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_expansions(**req_copy) @@ -2880,6 +3034,7 @@ def test_delete_expansions_value_error_with_retries(self): _service.disable_retries() self.test_delete_expansions_value_error() + # endregion ############################################################################## # End of Service: QueryModifications @@ -2890,7 +3045,8 @@ def test_delete_expansions_value_error_with_retries(self): ############################################################################## # region -class TestGetComponentSettings(): + +class TestGetComponentSettings: """ Test Class for get_component_settings """ @@ -2903,11 +3059,13 @@ def test_get_component_settings_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2915,7 +3073,7 @@ def test_get_component_settings_all_params(self): # Invoke method response = _service.get_component_settings( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -2939,11 +3097,13 @@ def test_get_component_settings_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2953,7 +3113,7 @@ def test_get_component_settings_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_component_settings(**req_copy) @@ -2966,6 +3126,7 @@ def test_get_component_settings_value_error_with_retries(self): _service.disable_retries() self.test_get_component_settings_value_error() + # endregion ############################################################################## # End of Service: ComponentSettings @@ -2976,7 +3137,8 @@ def test_get_component_settings_value_error_with_retries(self): ############################################################################## # region -class TestListTrainingQueries(): + +class TestListTrainingQueries: """ Test Class for list_training_queries """ @@ -2989,11 +3151,13 @@ def test_list_training_queries_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3001,7 +3165,7 @@ def test_list_training_queries_all_params(self): # Invoke method response = _service.list_training_queries( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3025,11 +3189,13 @@ def test_list_training_queries_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3039,7 +3205,7 @@ def test_list_training_queries_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_queries(**req_copy) @@ -3052,7 +3218,8 @@ def test_list_training_queries_value_error_with_retries(self): _service.disable_retries() self.test_list_training_queries_value_error() -class TestDeleteTrainingQueries(): + +class TestDeleteTrainingQueries: """ Test Class for delete_training_queries """ @@ -3064,9 +3231,11 @@ def test_delete_training_queries_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3074,7 +3243,7 @@ def test_delete_training_queries_all_params(self): # Invoke method response = _service.delete_training_queries( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3097,9 +3266,11 @@ def test_delete_training_queries_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3109,7 +3280,7 @@ def test_delete_training_queries_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_queries(**req_copy) @@ -3122,7 +3293,8 @@ def test_delete_training_queries_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_queries_value_error() -class TestCreateTrainingQuery(): + +class TestCreateTrainingQuery: """ Test Class for create_training_query """ @@ -3135,11 +3307,13 @@ def test_create_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3159,7 +3333,7 @@ def test_create_training_query_all_params(self): natural_language_query, examples, filter=filter, - headers={} + headers={}, ) # Check for correct operation @@ -3188,11 +3362,13 @@ def test_create_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3213,7 +3389,7 @@ def test_create_training_query_value_error(self): "examples": examples, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_training_query(**req_copy) @@ -3226,7 +3402,8 @@ def test_create_training_query_value_error_with_retries(self): _service.disable_retries() self.test_create_training_query_value_error() -class TestGetTrainingQuery(): + +class TestGetTrainingQuery: """ Test Class for get_training_query """ @@ -3239,11 +3416,13 @@ def test_get_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3253,7 +3432,7 @@ def test_get_training_query_all_params(self): response = _service.get_training_query( project_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -3277,11 +3456,13 @@ def test_get_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3293,7 +3474,7 @@ def test_get_training_query_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_query(**req_copy) @@ -3306,7 +3487,8 @@ def test_get_training_query_value_error_with_retries(self): _service.disable_retries() self.test_get_training_query_value_error() -class TestUpdateTrainingQuery(): + +class TestUpdateTrainingQuery: """ Test Class for update_training_query """ @@ -3319,11 +3501,13 @@ def test_update_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3345,7 +3529,7 @@ def test_update_training_query_all_params(self): natural_language_query, examples, filter=filter, - headers={} + headers={}, ) # Check for correct operation @@ -3374,11 +3558,13 @@ def test_update_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3401,7 +3587,7 @@ def test_update_training_query_value_error(self): "examples": examples, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_training_query(**req_copy) @@ -3414,7 +3600,8 @@ def test_update_training_query_value_error_with_retries(self): _service.disable_retries() self.test_update_training_query_value_error() -class TestDeleteTrainingQuery(): + +class TestDeleteTrainingQuery: """ Test Class for delete_training_query """ @@ -3426,9 +3613,11 @@ def test_delete_training_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3438,7 +3627,7 @@ def test_delete_training_query_all_params(self): response = _service.delete_training_query( project_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -3461,9 +3650,11 @@ def test_delete_training_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3475,7 +3666,7 @@ def test_delete_training_query_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_query(**req_copy) @@ -3488,6 +3679,7 @@ def test_delete_training_query_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_query_value_error() + # endregion ############################################################################## # End of Service: TrainingData @@ -3498,7 +3690,8 @@ def test_delete_training_query_value_error_with_retries(self): ############################################################################## # region -class TestListEnrichments(): + +class TestListEnrichments: """ Test Class for list_enrichments """ @@ -3510,12 +3703,14 @@ def test_list_enrichments_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3523,7 +3718,7 @@ def test_list_enrichments_all_params(self): # Invoke method response = _service.list_enrichments( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3546,12 +3741,14 @@ def test_list_enrichments_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3561,7 +3758,7 @@ def test_list_enrichments_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_enrichments(**req_copy) @@ -3574,7 +3771,8 @@ def test_list_enrichments_value_error_with_retries(self): _service.disable_retries() self.test_list_enrichments_value_error() -class TestCreateEnrichment(): + +class TestCreateEnrichment: """ Test Class for create_enrichment """ @@ -3586,12 +3784,19 @@ def test_create_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3602,7 +3807,12 @@ def test_create_enrichment_all_params(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3621,7 +3831,7 @@ def test_create_enrichment_all_params(self): project_id, enrichment, file=file, - headers={} + headers={}, ) # Check for correct operation @@ -3644,12 +3854,19 @@ def test_create_enrichment_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3660,7 +3877,12 @@ def test_create_enrichment_required_params(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3677,7 +3899,7 @@ def test_create_enrichment_required_params(self): response = _service.create_enrichment( project_id, enrichment, - headers={} + headers={}, ) # Check for correct operation @@ -3700,12 +3922,19 @@ def test_create_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3716,7 +3945,12 @@ def test_create_enrichment_value_error(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3735,7 +3969,7 @@ def test_create_enrichment_value_error(self): "enrichment": enrichment, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_enrichment(**req_copy) @@ -3748,7 +3982,8 @@ def test_create_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_create_enrichment_value_error() -class TestGetEnrichment(): + +class TestGetEnrichment: """ Test Class for get_enrichment """ @@ -3760,12 +3995,14 @@ def test_get_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3775,7 +4012,7 @@ def test_get_enrichment_all_params(self): response = _service.get_enrichment( project_id, enrichment_id, - headers={} + headers={}, ) # Check for correct operation @@ -3798,12 +4035,14 @@ def test_get_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3815,7 +4054,7 @@ def test_get_enrichment_value_error(self): "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_enrichment(**req_copy) @@ -3828,7 +4067,8 @@ def test_get_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_get_enrichment_value_error() -class TestUpdateEnrichment(): + +class TestUpdateEnrichment: """ Test Class for update_enrichment """ @@ -3840,12 +4080,14 @@ def test_update_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3859,7 +4101,7 @@ def test_update_enrichment_all_params(self): enrichment_id, name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -3886,12 +4128,14 @@ def test_update_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3906,7 +4150,7 @@ def test_update_enrichment_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_enrichment(**req_copy) @@ -3919,7 +4163,8 @@ def test_update_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_update_enrichment_value_error() -class TestDeleteEnrichment(): + +class TestDeleteEnrichment: """ Test Class for delete_enrichment """ @@ -3931,9 +4176,11 @@ def test_delete_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3943,7 +4190,7 @@ def test_delete_enrichment_all_params(self): response = _service.delete_enrichment( project_id, enrichment_id, - headers={} + headers={}, ) # Check for correct operation @@ -3966,9 +4213,11 @@ def test_delete_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3980,7 +4229,7 @@ def test_delete_enrichment_value_error(self): "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_enrichment(**req_copy) @@ -3993,6 +4242,7 @@ def test_delete_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_delete_enrichment_value_error() + # endregion ############################################################################## # End of Service: Enrichments @@ -4003,7 +4253,8 @@ def test_delete_enrichment_value_error_with_retries(self): ############################################################################## # region -class TestListDocumentClassifiers(): + +class TestListDocumentClassifiers: """ Test Class for list_document_classifiers """ @@ -4016,11 +4267,13 @@ def test_list_document_classifiers_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4028,7 +4281,7 @@ def test_list_document_classifiers_all_params(self): # Invoke method response = _service.list_document_classifiers( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -4052,11 +4305,13 @@ def test_list_document_classifiers_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4066,7 +4321,7 @@ def test_list_document_classifiers_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_document_classifiers(**req_copy) @@ -4079,7 +4334,8 @@ def test_list_document_classifiers_value_error_with_retries(self): _service.disable_retries() self.test_list_document_classifiers_value_error() -class TestCreateDocumentClassifier(): + +class TestCreateDocumentClassifier: """ Test Class for create_document_classifier """ @@ -4092,11 +4348,13 @@ def test_create_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4128,7 +4386,7 @@ def test_create_document_classifier_all_params(self): training_data, classifier, test_data=test_data, - headers={} + headers={}, ) # Check for correct operation @@ -4152,11 +4410,13 @@ def test_create_document_classifier_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4186,7 +4446,7 @@ def test_create_document_classifier_required_params(self): project_id, training_data, classifier, - headers={} + headers={}, ) # Check for correct operation @@ -4210,11 +4470,13 @@ def test_create_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4246,7 +4508,7 @@ def test_create_document_classifier_value_error(self): "classifier": classifier, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_document_classifier(**req_copy) @@ -4259,7 +4521,8 @@ def test_create_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_create_document_classifier_value_error() -class TestGetDocumentClassifier(): + +class TestGetDocumentClassifier: """ Test Class for get_document_classifier """ @@ -4272,11 +4535,13 @@ def test_get_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4286,7 +4551,7 @@ def test_get_document_classifier_all_params(self): response = _service.get_document_classifier( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4310,11 +4575,13 @@ def test_get_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4326,7 +4593,7 @@ def test_get_document_classifier_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_classifier(**req_copy) @@ -4339,7 +4606,8 @@ def test_get_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_get_document_classifier_value_error() -class TestUpdateDocumentClassifier(): + +class TestUpdateDocumentClassifier: """ Test Class for update_document_classifier """ @@ -4352,11 +4620,13 @@ def test_update_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4377,7 +4647,7 @@ def test_update_document_classifier_all_params(self): classifier, training_data=training_data, test_data=test_data, - headers={} + headers={}, ) # Check for correct operation @@ -4401,11 +4671,13 @@ def test_update_document_classifier_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4422,7 +4694,7 @@ def test_update_document_classifier_required_params(self): project_id, classifier_id, classifier, - headers={} + headers={}, ) # Check for correct operation @@ -4446,11 +4718,13 @@ def test_update_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4469,7 +4743,7 @@ def test_update_document_classifier_value_error(self): "classifier": classifier, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document_classifier(**req_copy) @@ -4482,7 +4756,8 @@ def test_update_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_update_document_classifier_value_error() -class TestDeleteDocumentClassifier(): + +class TestDeleteDocumentClassifier: """ Test Class for delete_document_classifier """ @@ -4494,9 +4769,11 @@ def test_delete_document_classifier_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4506,7 +4783,7 @@ def test_delete_document_classifier_all_params(self): response = _service.delete_document_classifier( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4529,9 +4806,11 @@ def test_delete_document_classifier_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4543,7 +4822,7 @@ def test_delete_document_classifier_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document_classifier(**req_copy) @@ -4556,6 +4835,7 @@ def test_delete_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_classifier_value_error() + # endregion ############################################################################## # End of Service: DocumentClassifiers @@ -4566,7 +4846,8 @@ def test_delete_document_classifier_value_error_with_retries(self): ############################################################################## # region -class TestListDocumentClassifierModels(): + +class TestListDocumentClassifierModels: """ Test Class for list_document_classifier_models """ @@ -4579,11 +4860,13 @@ def test_list_document_classifier_models_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4593,7 +4876,7 @@ def test_list_document_classifier_models_all_params(self): response = _service.list_document_classifier_models( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4617,11 +4900,13 @@ def test_list_document_classifier_models_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4633,7 +4918,7 @@ def test_list_document_classifier_models_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_document_classifier_models(**req_copy) @@ -4646,7 +4931,8 @@ def test_list_document_classifier_models_value_error_with_retries(self): _service.disable_retries() self.test_list_document_classifier_models_value_error() -class TestCreateDocumentClassifierModel(): + +class TestCreateDocumentClassifierModel: """ Test Class for create_document_classifier_model """ @@ -4659,22 +4945,24 @@ def test_create_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' classifier_id = 'testString' name = 'testString' description = 'testString' - learning_rate = 0 + learning_rate = 0.1 l1_regularization_strengths = [1.0E-6] l2_regularization_strengths = [1.0E-6] - training_max_steps = 0 - improvement_ratio = 0 + training_max_steps = 10000000 + improvement_ratio = 0.000010 # Invoke method response = _service.create_document_classifier_model( @@ -4687,7 +4975,7 @@ def test_create_document_classifier_model_all_params(self): l2_regularization_strengths=l2_regularization_strengths, training_max_steps=training_max_steps, improvement_ratio=improvement_ratio, - headers={} + headers={}, ) # Check for correct operation @@ -4697,11 +4985,11 @@ def test_create_document_classifier_model_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['learning_rate'] == 0 + assert req_body['learning_rate'] == 0.1 assert req_body['l1_regularization_strengths'] == [1.0E-6] assert req_body['l2_regularization_strengths'] == [1.0E-6] - assert req_body['training_max_steps'] == 0 - assert req_body['improvement_ratio'] == 0 + assert req_body['training_max_steps'] == 10000000 + assert req_body['improvement_ratio'] == 0.000010 def test_create_document_classifier_model_all_params_with_retries(self): # Enable retries and run test_create_document_classifier_model_all_params. @@ -4720,22 +5008,24 @@ def test_create_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' classifier_id = 'testString' name = 'testString' description = 'testString' - learning_rate = 0 + learning_rate = 0.1 l1_regularization_strengths = [1.0E-6] l2_regularization_strengths = [1.0E-6] - training_max_steps = 0 - improvement_ratio = 0 + training_max_steps = 10000000 + improvement_ratio = 0.000010 # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -4744,7 +5034,7 @@ def test_create_document_classifier_model_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_document_classifier_model(**req_copy) @@ -4757,7 +5047,8 @@ def test_create_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_create_document_classifier_model_value_error() -class TestGetDocumentClassifierModel(): + +class TestGetDocumentClassifierModel: """ Test Class for get_document_classifier_model """ @@ -4770,11 +5061,13 @@ def test_get_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4786,7 +5079,7 @@ def test_get_document_classifier_model_all_params(self): project_id, classifier_id, model_id, - headers={} + headers={}, ) # Check for correct operation @@ -4810,11 +5103,13 @@ def test_get_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4828,7 +5123,7 @@ def test_get_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_classifier_model(**req_copy) @@ -4841,7 +5136,8 @@ def test_get_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_get_document_classifier_model_value_error() -class TestUpdateDocumentClassifierModel(): + +class TestUpdateDocumentClassifierModel: """ Test Class for update_document_classifier_model """ @@ -4854,11 +5150,13 @@ def test_update_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' @@ -4874,7 +5172,7 @@ def test_update_document_classifier_model_all_params(self): model_id, name=name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -4902,11 +5200,13 @@ def test_update_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' @@ -4922,7 +5222,7 @@ def test_update_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document_classifier_model(**req_copy) @@ -4935,7 +5235,8 @@ def test_update_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_update_document_classifier_model_value_error() -class TestDeleteDocumentClassifierModel(): + +class TestDeleteDocumentClassifierModel: """ Test Class for delete_document_classifier_model """ @@ -4947,9 +5248,11 @@ def test_delete_document_classifier_model_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4961,7 +5264,7 @@ def test_delete_document_classifier_model_all_params(self): project_id, classifier_id, model_id, - headers={} + headers={}, ) # Check for correct operation @@ -4984,9 +5287,11 @@ def test_delete_document_classifier_model_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -5000,7 +5305,7 @@ def test_delete_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document_classifier_model(**req_copy) @@ -5013,6 +5318,7 @@ def test_delete_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_classifier_model_value_error() + # endregion ############################################################################## # End of Service: DocumentClassifierModels @@ -5023,7 +5329,8 @@ def test_delete_document_classifier_model_value_error_with_retries(self): ############################################################################## # region -class TestAnalyzeDocument(): + +class TestAnalyzeDocument: """ Test Class for analyze_document """ @@ -5036,11 +5343,13 @@ def test_analyze_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5058,7 +5367,7 @@ def test_analyze_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -5082,11 +5391,13 @@ def test_analyze_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5096,7 +5407,7 @@ def test_analyze_document_required_params(self): response = _service.analyze_document( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -5120,11 +5431,13 @@ def test_analyze_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5136,7 +5449,7 @@ def test_analyze_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.analyze_document(**req_copy) @@ -5149,6 +5462,7 @@ def test_analyze_document_value_error_with_retries(self): _service.disable_retries() self.test_analyze_document_value_error() + # endregion ############################################################################## # End of Service: Analyze @@ -5159,7 +5473,8 @@ def test_analyze_document_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -5171,9 +5486,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5181,14 +5498,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -5208,9 +5525,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5220,7 +5539,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -5233,6 +5552,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -5243,7 +5563,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AnalyzedDocument(): + + +class TestModel_AnalyzedDocument: """ Test Class for AnalyzedDocument """ @@ -5255,10 +5577,10 @@ def test_analyzed_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - analyzed_result_model = {} # AnalyzedResult - analyzed_result_model['metadata'] = {'foo': 'bar'} + analyzed_result_model = {} # AnalyzedResult + analyzed_result_model['metadata'] = {'anyKey': 'anyValue'} analyzed_result_model['foo'] = 'testString' # Construct a json representation of a AnalyzedDocument model @@ -5281,7 +5603,8 @@ def test_analyzed_document_serialization(self): analyzed_document_model_json2 = analyzed_document_model.to_dict() assert analyzed_document_model_json2 == analyzed_document_model_json -class TestModel_AnalyzedResult(): + +class TestModel_AnalyzedResult: """ Test Class for AnalyzedResult """ @@ -5293,7 +5616,7 @@ def test_analyzed_result_serialization(self): # Construct a json representation of a AnalyzedResult model analyzed_result_model_json = {} - analyzed_result_model_json['metadata'] = {'foo': 'bar'} + analyzed_result_model_json['metadata'] = {'anyKey': 'anyValue'} analyzed_result_model_json['foo'] = 'testString' # Construct a model instance of AnalyzedResult by calling from_dict on the json representation @@ -5321,7 +5644,8 @@ def test_analyzed_result_serialization(self): actual_dict = analyzed_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_ClassifierFederatedModel(): + +class TestModel_ClassifierFederatedModel: """ Test Class for ClassifierFederatedModel """ @@ -5350,7 +5674,8 @@ def test_classifier_federated_model_serialization(self): classifier_federated_model_model_json2 = classifier_federated_model_model.to_dict() assert classifier_federated_model_model_json2 == classifier_federated_model_model_json -class TestModel_ClassifierModelEvaluation(): + +class TestModel_ClassifierModelEvaluation: """ Test Class for ClassifierModelEvaluation """ @@ -5362,17 +5687,17 @@ def test_classifier_model_evaluation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 @@ -5399,7 +5724,8 @@ def test_classifier_model_evaluation_serialization(self): classifier_model_evaluation_model_json2 = classifier_model_evaluation_model.to_dict() assert classifier_model_evaluation_model_json2 == classifier_model_evaluation_model_json -class TestModel_Collection(): + +class TestModel_Collection: """ Test Class for Collection """ @@ -5428,7 +5754,8 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestModel_CollectionDetails(): + +class TestModel_CollectionDetails: """ Test Class for CollectionDetails """ @@ -5440,7 +5767,7 @@ def test_collection_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - collection_enrichment_model = {} # CollectionEnrichment + collection_enrichment_model = {} # CollectionEnrichment collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] @@ -5466,7 +5793,8 @@ def test_collection_details_serialization(self): collection_details_model_json2 = collection_details_model.to_dict() assert collection_details_model_json2 == collection_details_model_json -class TestModel_CollectionDetailsSmartDocumentUnderstanding(): + +class TestModel_CollectionDetailsSmartDocumentUnderstanding: """ Test Class for CollectionDetailsSmartDocumentUnderstanding """ @@ -5496,7 +5824,8 @@ def test_collection_details_smart_document_understanding_serialization(self): collection_details_smart_document_understanding_model_json2 = collection_details_smart_document_understanding_model.to_dict() assert collection_details_smart_document_understanding_model_json2 == collection_details_smart_document_understanding_model_json -class TestModel_CollectionEnrichment(): + +class TestModel_CollectionEnrichment: """ Test Class for CollectionEnrichment """ @@ -5526,7 +5855,8 @@ def test_collection_enrichment_serialization(self): collection_enrichment_model_json2 = collection_enrichment_model.to_dict() assert collection_enrichment_model_json2 == collection_enrichment_model_json -class TestModel_Completions(): + +class TestModel_Completions: """ Test Class for Completions """ @@ -5555,7 +5885,8 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestModel_ComponentSettingsAggregation(): + +class TestModel_ComponentSettingsAggregation: """ Test Class for ComponentSettingsAggregation """ @@ -5587,7 +5918,8 @@ def test_component_settings_aggregation_serialization(self): component_settings_aggregation_model_json2 = component_settings_aggregation_model.to_dict() assert component_settings_aggregation_model_json2 == component_settings_aggregation_model_json -class TestModel_ComponentSettingsFieldsShown(): + +class TestModel_ComponentSettingsFieldsShown: """ Test Class for ComponentSettingsFieldsShown """ @@ -5599,11 +5931,11 @@ def test_component_settings_fields_shown_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody component_settings_fields_shown_body_model['use_passage'] = True component_settings_fields_shown_body_model['field'] = 'testString' - component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle component_settings_fields_shown_title_model['field'] = 'testString' # Construct a json representation of a ComponentSettingsFieldsShown model @@ -5626,7 +5958,8 @@ def test_component_settings_fields_shown_serialization(self): component_settings_fields_shown_model_json2 = component_settings_fields_shown_model.to_dict() assert component_settings_fields_shown_model_json2 == component_settings_fields_shown_model_json -class TestModel_ComponentSettingsFieldsShownBody(): + +class TestModel_ComponentSettingsFieldsShownBody: """ Test Class for ComponentSettingsFieldsShownBody """ @@ -5656,7 +5989,8 @@ def test_component_settings_fields_shown_body_serialization(self): component_settings_fields_shown_body_model_json2 = component_settings_fields_shown_body_model.to_dict() assert component_settings_fields_shown_body_model_json2 == component_settings_fields_shown_body_model_json -class TestModel_ComponentSettingsFieldsShownTitle(): + +class TestModel_ComponentSettingsFieldsShownTitle: """ Test Class for ComponentSettingsFieldsShownTitle """ @@ -5685,7 +6019,8 @@ def test_component_settings_fields_shown_title_serialization(self): component_settings_fields_shown_title_model_json2 = component_settings_fields_shown_title_model.to_dict() assert component_settings_fields_shown_title_model_json2 == component_settings_fields_shown_title_model_json -class TestModel_ComponentSettingsResponse(): + +class TestModel_ComponentSettingsResponse: """ Test Class for ComponentSettingsResponse """ @@ -5697,18 +6032,18 @@ def test_component_settings_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody component_settings_fields_shown_body_model['use_passage'] = True component_settings_fields_shown_body_model['field'] = 'testString' - component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle component_settings_fields_shown_title_model['field'] = 'testString' - component_settings_fields_shown_model = {} # ComponentSettingsFieldsShown + component_settings_fields_shown_model = {} # ComponentSettingsFieldsShown component_settings_fields_shown_model['body'] = component_settings_fields_shown_body_model component_settings_fields_shown_model['title'] = component_settings_fields_shown_title_model - component_settings_aggregation_model = {} # ComponentSettingsAggregation + component_settings_aggregation_model = {} # ComponentSettingsAggregation component_settings_aggregation_model['name'] = 'testString' component_settings_aggregation_model['label'] = 'testString' component_settings_aggregation_model['multiple_selections_allowed'] = True @@ -5737,7 +6072,8 @@ def test_component_settings_response_serialization(self): component_settings_response_model_json2 = component_settings_response_model.to_dict() assert component_settings_response_model_json2 == component_settings_response_model_json -class TestModel_CreateDocumentClassifier(): + +class TestModel_CreateDocumentClassifier: """ Test Class for CreateDocumentClassifier """ @@ -5749,11 +6085,11 @@ def test_create_document_classifier_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' # Construct a json representation of a CreateDocumentClassifier model @@ -5780,7 +6116,8 @@ def test_create_document_classifier_serialization(self): create_document_classifier_model_json2 = create_document_classifier_model.to_dict() assert create_document_classifier_model_json2 == create_document_classifier_model_json -class TestModel_CreateEnrichment(): + +class TestModel_CreateEnrichment: """ Test Class for CreateEnrichment """ @@ -5792,7 +6129,11 @@ def test_create_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -5800,7 +6141,12 @@ def test_create_enrichment_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a json representation of a CreateEnrichment model create_enrichment_model_json = {} @@ -5824,7 +6170,8 @@ def test_create_enrichment_serialization(self): create_enrichment_model_json2 = create_enrichment_model.to_dict() assert create_enrichment_model_json2 == create_enrichment_model_json -class TestModel_DefaultQueryParams(): + +class TestModel_DefaultQueryParams: """ Test Class for DefaultQueryParams """ @@ -5836,7 +6183,7 @@ def test_default_query_params_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 default_query_params_passages_model['fields'] = ['testString'] @@ -5844,12 +6191,12 @@ def test_default_query_params_serialization(self): default_query_params_passages_model['per_document'] = True default_query_params_passages_model['max_per_document'] = 38 - default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 - default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements default_query_params_suggested_refinements_model['enabled'] = True default_query_params_suggested_refinements_model['count'] = 38 @@ -5881,7 +6228,8 @@ def test_default_query_params_serialization(self): default_query_params_model_json2 = default_query_params_model.to_dict() assert default_query_params_model_json2 == default_query_params_model_json -class TestModel_DefaultQueryParamsPassages(): + +class TestModel_DefaultQueryParamsPassages: """ Test Class for DefaultQueryParamsPassages """ @@ -5915,7 +6263,8 @@ def test_default_query_params_passages_serialization(self): default_query_params_passages_model_json2 = default_query_params_passages_model.to_dict() assert default_query_params_passages_model_json2 == default_query_params_passages_model_json -class TestModel_DefaultQueryParamsSuggestedRefinements(): + +class TestModel_DefaultQueryParamsSuggestedRefinements: """ Test Class for DefaultQueryParamsSuggestedRefinements """ @@ -5945,7 +6294,8 @@ def test_default_query_params_suggested_refinements_serialization(self): default_query_params_suggested_refinements_model_json2 = default_query_params_suggested_refinements_model.to_dict() assert default_query_params_suggested_refinements_model_json2 == default_query_params_suggested_refinements_model_json -class TestModel_DefaultQueryParamsTableResults(): + +class TestModel_DefaultQueryParamsTableResults: """ Test Class for DefaultQueryParamsTableResults """ @@ -5959,7 +6309,7 @@ def test_default_query_params_table_results_serialization(self): default_query_params_table_results_model_json = {} default_query_params_table_results_model_json['enabled'] = True default_query_params_table_results_model_json['count'] = 38 - default_query_params_table_results_model_json['per_document'] = 38 + default_query_params_table_results_model_json['per_document'] = 0 # Construct a model instance of DefaultQueryParamsTableResults by calling from_dict on the json representation default_query_params_table_results_model = DefaultQueryParamsTableResults.from_dict(default_query_params_table_results_model_json) @@ -5976,7 +6326,8 @@ def test_default_query_params_table_results_serialization(self): default_query_params_table_results_model_json2 = default_query_params_table_results_model.to_dict() assert default_query_params_table_results_model_json2 == default_query_params_table_results_model_json -class TestModel_DeleteDocumentResponse(): + +class TestModel_DeleteDocumentResponse: """ Test Class for DeleteDocumentResponse """ @@ -6006,7 +6357,8 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestModel_DocumentAccepted(): + +class TestModel_DocumentAccepted: """ Test Class for DocumentAccepted """ @@ -6036,7 +6388,8 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestModel_DocumentAttribute(): + +class TestModel_DocumentAttribute: """ Test Class for DocumentAttribute """ @@ -6048,7 +6401,7 @@ def test_document_attribute_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -6073,7 +6426,8 @@ def test_document_attribute_serialization(self): document_attribute_model_json2 = document_attribute_model.to_dict() assert document_attribute_model_json2 == document_attribute_model_json -class TestModel_DocumentClassifier(): + +class TestModel_DocumentClassifier: """ Test Class for DocumentClassifier """ @@ -6085,11 +6439,11 @@ def test_document_classifier_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' # Construct a json representation of a DocumentClassifier model @@ -6119,7 +6473,8 @@ def test_document_classifier_serialization(self): document_classifier_model_json2 = document_classifier_model.to_dict() assert document_classifier_model_json2 == document_classifier_model_json -class TestModel_DocumentClassifierEnrichment(): + +class TestModel_DocumentClassifierEnrichment: """ Test Class for DocumentClassifierEnrichment """ @@ -6149,7 +6504,8 @@ def test_document_classifier_enrichment_serialization(self): document_classifier_enrichment_model_json2 = document_classifier_enrichment_model.to_dict() assert document_classifier_enrichment_model_json2 == document_classifier_enrichment_model_json -class TestModel_DocumentClassifierModel(): + +class TestModel_DocumentClassifierModel: """ Test Class for DocumentClassifierModel """ @@ -6161,23 +6517,23 @@ def test_document_classifier_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 per_class_model_evaluation_model['f1'] = 0 - classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model = {} # ClassifierModelEvaluation classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] @@ -6207,7 +6563,8 @@ def test_document_classifier_model_serialization(self): document_classifier_model_model_json2 = document_classifier_model_model.to_dict() assert document_classifier_model_model_json2 == document_classifier_model_model_json -class TestModel_DocumentClassifierModels(): + +class TestModel_DocumentClassifierModels: """ Test Class for DocumentClassifierModels """ @@ -6219,28 +6576,28 @@ def test_document_classifier_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 per_class_model_evaluation_model['f1'] = 0 - classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model = {} # ClassifierModelEvaluation classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] - document_classifier_model_model = {} # DocumentClassifierModel + document_classifier_model_model = {} # DocumentClassifierModel document_classifier_model_model['name'] = 'testString' document_classifier_model_model['description'] = 'testString' document_classifier_model_model['training_data_file'] = 'testString' @@ -6268,7 +6625,8 @@ def test_document_classifier_models_serialization(self): document_classifier_models_model_json2 = document_classifier_models_model.to_dict() assert document_classifier_models_model_json2 == document_classifier_models_model_json -class TestModel_DocumentClassifiers(): + +class TestModel_DocumentClassifiers: """ Test Class for DocumentClassifiers """ @@ -6280,14 +6638,14 @@ def test_document_classifiers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' - document_classifier_model = {} # DocumentClassifier + document_classifier_model = {} # DocumentClassifier document_classifier_model['name'] = 'testString' document_classifier_model['description'] = 'testString' document_classifier_model['language'] = 'en' @@ -6317,7 +6675,8 @@ def test_document_classifiers_serialization(self): document_classifiers_model_json2 = document_classifiers_model.to_dict() assert document_classifiers_model_json2 == document_classifiers_model_json -class TestModel_DocumentDetails(): + +class TestModel_DocumentDetails: """ Test Class for DocumentDetails """ @@ -6329,9 +6688,9 @@ def test_document_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True document_details_children_model['count'] = 38 @@ -6359,7 +6718,8 @@ def test_document_details_serialization(self): document_details_model_json2 = document_details_model.to_dict() assert document_details_model_json2 == document_details_model_json -class TestModel_DocumentDetailsChildren(): + +class TestModel_DocumentDetailsChildren: """ Test Class for DocumentDetailsChildren """ @@ -6389,7 +6749,8 @@ def test_document_details_children_serialization(self): document_details_children_model_json2 = document_details_children_model.to_dict() assert document_details_children_model_json2 == document_details_children_model_json -class TestModel_Enrichment(): + +class TestModel_Enrichment: """ Test Class for Enrichment """ @@ -6401,7 +6762,11 @@ def test_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -6409,7 +6774,12 @@ def test_enrichment_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a json representation of a Enrichment model enrichment_model_json = {} @@ -6433,7 +6803,8 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestModel_EnrichmentOptions(): + +class TestModel_EnrichmentOptions: """ Test Class for EnrichmentOptions """ @@ -6443,6 +6814,12 @@ def test_enrichment_options_serialization(self): Test serialization/deserialization for EnrichmentOptions """ + # Construct dict forms of any model objects needed in order to build this model. + + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + # Construct a json representation of a EnrichmentOptions model enrichment_options_model_json = {} enrichment_options_model_json['languages'] = ['testString'] @@ -6452,7 +6829,12 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json['classifier_id'] = 'testString' enrichment_options_model_json['model_id'] = 'testString' enrichment_options_model_json['confidence_threshold'] = 0 - enrichment_options_model_json['top_k'] = 38 + enrichment_options_model_json['top_k'] = 0 + enrichment_options_model_json['url'] = 'testString' + enrichment_options_model_json['version'] = '2023-03-31' + enrichment_options_model_json['secret'] = 'testString' + enrichment_options_model_json['headers'] = webhook_header_model + enrichment_options_model_json['location_encoding'] = '`utf-16`' # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) @@ -6469,7 +6851,8 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestModel_Enrichments(): + +class TestModel_Enrichments: """ Test Class for Enrichments """ @@ -6481,7 +6864,11 @@ def test_enrichments_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -6489,9 +6876,14 @@ def test_enrichments_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 - - enrichment_model = {} # Enrichment + enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' + + enrichment_model = {} # Enrichment enrichment_model['name'] = 'testString' enrichment_model['description'] = 'testString' enrichment_model['type'] = 'part_of_speech' @@ -6516,7 +6908,8 @@ def test_enrichments_serialization(self): enrichments_model_json2 = enrichments_model.to_dict() assert enrichments_model_json2 == enrichments_model_json -class TestModel_Expansion(): + +class TestModel_Expansion: """ Test Class for Expansion """ @@ -6546,7 +6939,8 @@ def test_expansion_serialization(self): expansion_model_json2 = expansion_model.to_dict() assert expansion_model_json2 == expansion_model_json -class TestModel_Expansions(): + +class TestModel_Expansions: """ Test Class for Expansions """ @@ -6558,7 +6952,7 @@ def test_expansions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - expansion_model = {} # Expansion + expansion_model = {} # Expansion expansion_model['input_terms'] = ['testString'] expansion_model['expanded_terms'] = ['testString'] @@ -6581,7 +6975,8 @@ def test_expansions_serialization(self): expansions_model_json2 = expansions_model.to_dict() assert expansions_model_json2 == expansions_model_json -class TestModel_Field(): + +class TestModel_Field: """ Test Class for Field """ @@ -6609,7 +7004,8 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestModel_ListCollectionsResponse(): + +class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse """ @@ -6621,7 +7017,7 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - collection_model = {} # Collection + collection_model = {} # Collection collection_model['name'] = 'example' # Construct a json representation of a ListCollectionsResponse model @@ -6643,7 +7039,8 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestModel_ListDocumentsResponse(): + +class TestModel_ListDocumentsResponse: """ Test Class for ListDocumentsResponse """ @@ -6655,13 +7052,13 @@ def test_list_documents_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True document_details_children_model['count'] = 38 - document_details_model = {} # DocumentDetails + document_details_model = {} # DocumentDetails document_details_model['status'] = 'available' document_details_model['notices'] = [notice_model] document_details_model['children'] = document_details_children_model @@ -6689,7 +7086,8 @@ def test_list_documents_response_serialization(self): list_documents_response_model_json2 = list_documents_response_model.to_dict() assert list_documents_response_model_json2 == list_documents_response_model_json -class TestModel_ListFieldsResponse(): + +class TestModel_ListFieldsResponse: """ Test Class for ListFieldsResponse """ @@ -6701,7 +7099,7 @@ def test_list_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - field_model = {} # Field + field_model = {} # Field # Construct a json representation of a ListFieldsResponse model list_fields_response_model_json = {} @@ -6722,7 +7120,8 @@ def test_list_fields_response_serialization(self): list_fields_response_model_json2 = list_fields_response_model.to_dict() assert list_fields_response_model_json2 == list_fields_response_model_json -class TestModel_ListProjectsResponse(): + +class TestModel_ListProjectsResponse: """ Test Class for ListProjectsResponse """ @@ -6734,7 +7133,7 @@ def test_list_projects_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_model = {} # ProjectListDetails + project_list_details_model = {} # ProjectListDetails project_list_details_model['name'] = 'testString' project_list_details_model['type'] = 'document_retrieval' @@ -6757,7 +7156,8 @@ def test_list_projects_response_serialization(self): list_projects_response_model_json2 = list_projects_response_model.to_dict() assert list_projects_response_model_json2 == list_projects_response_model_json -class TestModel_ModelEvaluationMacroAverage(): + +class TestModel_ModelEvaluationMacroAverage: """ Test Class for ModelEvaluationMacroAverage """ @@ -6788,7 +7188,8 @@ def test_model_evaluation_macro_average_serialization(self): model_evaluation_macro_average_model_json2 = model_evaluation_macro_average_model.to_dict() assert model_evaluation_macro_average_model_json2 == model_evaluation_macro_average_model_json -class TestModel_ModelEvaluationMicroAverage(): + +class TestModel_ModelEvaluationMicroAverage: """ Test Class for ModelEvaluationMicroAverage """ @@ -6819,7 +7220,8 @@ def test_model_evaluation_micro_average_serialization(self): model_evaluation_micro_average_model_json2 = model_evaluation_micro_average_model.to_dict() assert model_evaluation_micro_average_model_json2 == model_evaluation_micro_average_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -6847,7 +7249,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_PerClassModelEvaluation(): + +class TestModel_PerClassModelEvaluation: """ Test Class for PerClassModelEvaluation """ @@ -6879,7 +7282,8 @@ def test_per_class_model_evaluation_serialization(self): per_class_model_evaluation_model_json2 = per_class_model_evaluation_model.to_dict() assert per_class_model_evaluation_model_json2 == per_class_model_evaluation_model_json -class TestModel_ProjectDetails(): + +class TestModel_ProjectDetails: """ Test Class for ProjectDetails """ @@ -6891,7 +7295,7 @@ def test_project_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 default_query_params_passages_model['fields'] = ['testString'] @@ -6899,16 +7303,16 @@ def test_project_details_serialization(self): default_query_params_passages_model['per_document'] = True default_query_params_passages_model['max_per_document'] = 38 - default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 - default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements default_query_params_suggested_refinements_model['enabled'] = True default_query_params_suggested_refinements_model['count'] = 38 - default_query_params_model = {} # DefaultQueryParams + default_query_params_model = {} # DefaultQueryParams default_query_params_model['collection_ids'] = ['testString'] default_query_params_model['passages'] = default_query_params_passages_model default_query_params_model['table_results'] = default_query_params_table_results_model @@ -6941,7 +7345,8 @@ def test_project_details_serialization(self): project_details_model_json2 = project_details_model.to_dict() assert project_details_model_json2 == project_details_model_json -class TestModel_ProjectListDetails(): + +class TestModel_ProjectListDetails: """ Test Class for ProjectListDetails """ @@ -6971,7 +7376,8 @@ def test_project_list_details_serialization(self): project_list_details_model_json2 = project_list_details_model.to_dict() assert project_list_details_model_json2 == project_list_details_model_json -class TestModel_ProjectListDetailsRelevancyTrainingStatus(): + +class TestModel_ProjectListDetailsRelevancyTrainingStatus: """ Test Class for ProjectListDetailsRelevancyTrainingStatus """ @@ -7008,7 +7414,8 @@ def test_project_list_details_relevancy_training_status_serialization(self): project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json -class TestModel_QueryGroupByAggregationResult(): + +class TestModel_QueryGroupByAggregationResult: """ Test Class for QueryGroupByAggregationResult """ @@ -7025,7 +7432,7 @@ def test_query_group_by_aggregation_result_serialization(self): query_group_by_aggregation_result_model_json['relevancy'] = 72.5 query_group_by_aggregation_result_model_json['total_matching_documents'] = 38 query_group_by_aggregation_result_model_json['estimated_matching_results'] = 72.5 - query_group_by_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_group_by_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation query_group_by_aggregation_result_model = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json) @@ -7042,7 +7449,8 @@ def test_query_group_by_aggregation_result_serialization(self): query_group_by_aggregation_result_model_json2 = query_group_by_aggregation_result_model.to_dict() assert query_group_by_aggregation_result_model_json2 == query_group_by_aggregation_result_model_json -class TestModel_QueryHistogramAggregationResult(): + +class TestModel_QueryHistogramAggregationResult: """ Test Class for QueryHistogramAggregationResult """ @@ -7056,7 +7464,7 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json = {} query_histogram_aggregation_result_model_json['key'] = 26 query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_histogram_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) @@ -7073,7 +7481,8 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json -class TestModel_QueryLargePassages(): + +class TestModel_QueryLargePassages: """ Test Class for QueryLargePassages """ @@ -7092,7 +7501,7 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json['count'] = 400 query_large_passages_model_json['characters'] = 50 query_large_passages_model_json['find_answers'] = False - query_large_passages_model_json['max_answers_per_passage'] = 38 + query_large_passages_model_json['max_answers_per_passage'] = 1 # Construct a model instance of QueryLargePassages by calling from_dict on the json representation query_large_passages_model = QueryLargePassages.from_dict(query_large_passages_model_json) @@ -7109,7 +7518,8 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json2 = query_large_passages_model.to_dict() assert query_large_passages_model_json2 == query_large_passages_model_json -class TestModel_QueryLargeSimilar(): + +class TestModel_QueryLargeSimilar: """ Test Class for QueryLargeSimilar """ @@ -7140,7 +7550,8 @@ def test_query_large_similar_serialization(self): query_large_similar_model_json2 = query_large_similar_model.to_dict() assert query_large_similar_model_json2 == query_large_similar_model_json -class TestModel_QueryLargeSuggestedRefinements(): + +class TestModel_QueryLargeSuggestedRefinements: """ Test Class for QueryLargeSuggestedRefinements """ @@ -7170,7 +7581,8 @@ def test_query_large_suggested_refinements_serialization(self): query_large_suggested_refinements_model_json2 = query_large_suggested_refinements_model.to_dict() assert query_large_suggested_refinements_model_json2 == query_large_suggested_refinements_model_json -class TestModel_QueryLargeTableResults(): + +class TestModel_QueryLargeTableResults: """ Test Class for QueryLargeTableResults """ @@ -7200,7 +7612,8 @@ def test_query_large_table_results_serialization(self): query_large_table_results_model_json2 = query_large_table_results_model.to_dict() assert query_large_table_results_model_json2 == query_large_table_results_model_json -class TestModel_QueryNoticesResponse(): + +class TestModel_QueryNoticesResponse: """ Test Class for QueryNoticesResponse """ @@ -7212,7 +7625,7 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a QueryNoticesResponse model query_notices_response_model_json = {} @@ -7234,7 +7647,8 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestModel_QueryPairAggregationResult(): + +class TestModel_QueryPairAggregationResult: """ Test Class for QueryPairAggregationResult """ @@ -7246,7 +7660,7 @@ def test_query_pair_aggregation_result_serialization(self): # Construct a json representation of a QueryPairAggregationResult model query_pair_aggregation_result_model_json = {} - query_pair_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_pair_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation query_pair_aggregation_result_model = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json) @@ -7263,7 +7677,8 @@ def test_query_pair_aggregation_result_serialization(self): query_pair_aggregation_result_model_json2 = query_pair_aggregation_result_model.to_dict() assert query_pair_aggregation_result_model_json2 == query_pair_aggregation_result_model_json -class TestModel_QueryResponse(): + +class TestModel_QueryResponse: """ Test Class for QueryResponse """ @@ -7275,70 +7690,70 @@ def test_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 0 - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 result_passage_answer_model['confidence'] = 0 - query_result_passage_model = {} # QueryResultPassage + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' query_result_passage_model['answers'] = [result_passage_answer_model] - query_result_model = {} # QueryResult + query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' - query_result_model['metadata'] = {'foo': 'bar'} + query_result_model['metadata'] = {'anyKey': 'anyValue'} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] query_result_model['id'] = 'watson-generated ID' - query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model = {} # QueryTermAggregationResult query_term_aggregation_result_model['key'] = 'active' query_term_aggregation_result_model['matching_results'] = 34 query_term_aggregation_result_model['relevancy'] = 72.5 query_term_aggregation_result_model['total_matching_documents'] = 38 query_term_aggregation_result_model['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] - query_aggregation_model = {} # QueryAggregationQueryTermAggregation + query_aggregation_model = {} # QueryAggregationQueryTermAggregation query_aggregation_model['type'] = 'term' query_aggregation_model['field'] = 'field' query_aggregation_model['count'] = 1 query_aggregation_model['name'] = 'testString' query_aggregation_model['results'] = [query_term_aggregation_result_model] - retrieval_details_model = {} # RetrievalDetails + retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' - query_suggested_refinement_model = {} # QuerySuggestedRefinement + query_suggested_refinement_model = {} # QuerySuggestedRefinement query_suggested_refinement_model['text'] = 'testString' - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -7348,9 +7763,9 @@ def test_query_response_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -7358,44 +7773,26 @@ def test_query_response_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -7403,15 +7800,15 @@ def test_query_response_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] - table_result_table_model = {} # TableResultTable + table_result_table_model = {} # TableResultTable table_result_table_model['location'] = table_element_location_model table_result_table_model['text'] = 'testString' table_result_table_model['section_title'] = table_text_location_model @@ -7423,7 +7820,7 @@ def test_query_response_serialization(self): table_result_table_model['body_cells'] = [table_body_cells_model] table_result_table_model['contexts'] = [table_text_location_model] - query_table_result_model = {} # QueryTableResult + query_table_result_model = {} # QueryTableResult query_table_result_model['table_id'] = 'testString' query_table_result_model['source_document_id'] = 'testString' query_table_result_model['collection_id'] = 'testString' @@ -7431,7 +7828,7 @@ def test_query_response_serialization(self): query_table_result_model['table_html_offset'] = 38 query_table_result_model['table'] = table_result_table_model - query_response_passage_model = {} # QueryResponsePassage + query_response_passage_model = {} # QueryResponsePassage query_response_passage_model['passage_text'] = 'testString' query_response_passage_model['passage_score'] = 72.5 query_response_passage_model['document_id'] = 'testString' @@ -7467,7 +7864,8 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestModel_QueryResponsePassage(): + +class TestModel_QueryResponsePassage: """ Test Class for QueryResponsePassage """ @@ -7479,7 +7877,7 @@ def test_query_response_passage_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 @@ -7511,7 +7909,8 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json2 = query_response_passage_model.to_dict() assert query_response_passage_model_json2 == query_response_passage_model_json -class TestModel_QueryResult(): + +class TestModel_QueryResult: """ Test Class for QueryResult """ @@ -7523,18 +7922,18 @@ def test_query_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 0 - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 result_passage_answer_model['confidence'] = 0 - query_result_passage_model = {} # QueryResultPassage + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 @@ -7544,7 +7943,7 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['document_id'] = 'testString' - query_result_model_json['metadata'] = {'foo': 'bar'} + query_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['document_passages'] = [query_result_passage_model] query_result_model_json['foo'] = 'testString' @@ -7574,7 +7973,8 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryResultMetadata(): + +class TestModel_QueryResultMetadata: """ Test Class for QueryResultMetadata """ @@ -7605,7 +8005,8 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestModel_QueryResultPassage(): + +class TestModel_QueryResultPassage: """ Test Class for QueryResultPassage """ @@ -7617,7 +8018,7 @@ def test_query_result_passage_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 @@ -7646,7 +8047,8 @@ def test_query_result_passage_serialization(self): query_result_passage_model_json2 = query_result_passage_model.to_dict() assert query_result_passage_model_json2 == query_result_passage_model_json -class TestModel_QuerySuggestedRefinement(): + +class TestModel_QuerySuggestedRefinement: """ Test Class for QuerySuggestedRefinement """ @@ -7675,7 +8077,8 @@ def test_query_suggested_refinement_serialization(self): query_suggested_refinement_model_json2 = query_suggested_refinement_model.to_dict() assert query_suggested_refinement_model_json2 == query_suggested_refinement_model_json -class TestModel_QueryTableResult(): + +class TestModel_QueryTableResult: """ Test Class for QueryTableResult """ @@ -7687,24 +8090,24 @@ def test_query_table_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -7714,9 +8117,9 @@ def test_query_table_result_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -7724,44 +8127,26 @@ def test_query_table_result_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -7769,15 +8154,15 @@ def test_query_table_result_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] - table_result_table_model = {} # TableResultTable + table_result_table_model = {} # TableResultTable table_result_table_model['location'] = table_element_location_model table_result_table_model['text'] = 'testString' table_result_table_model['section_title'] = table_text_location_model @@ -7813,7 +8198,8 @@ def test_query_table_result_serialization(self): query_table_result_model_json2 = query_table_result_model.to_dict() assert query_table_result_model_json2 == query_table_result_model_json -class TestModel_QueryTermAggregationResult(): + +class TestModel_QueryTermAggregationResult: """ Test Class for QueryTermAggregationResult """ @@ -7830,7 +8216,7 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json['relevancy'] = 72.5 query_term_aggregation_result_model_json['total_matching_documents'] = 38 query_term_aggregation_result_model_json['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) @@ -7847,7 +8233,8 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json -class TestModel_QueryTimesliceAggregationResult(): + +class TestModel_QueryTimesliceAggregationResult: """ Test Class for QueryTimesliceAggregationResult """ @@ -7862,7 +8249,7 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' query_timeslice_aggregation_result_model_json['key'] = 26 query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_timeslice_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) @@ -7879,7 +8266,8 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json -class TestModel_QueryTopHitsAggregationResult(): + +class TestModel_QueryTopHitsAggregationResult: """ Test Class for QueryTopHitsAggregationResult """ @@ -7892,7 +8280,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -7909,7 +8297,8 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json -class TestModel_QueryTopicAggregationResult(): + +class TestModel_QueryTopicAggregationResult: """ Test Class for QueryTopicAggregationResult """ @@ -7921,7 +8310,7 @@ def test_query_topic_aggregation_result_serialization(self): # Construct a json representation of a QueryTopicAggregationResult model query_topic_aggregation_result_model_json = {} - query_topic_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_topic_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation query_topic_aggregation_result_model = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json) @@ -7938,7 +8327,8 @@ def test_query_topic_aggregation_result_serialization(self): query_topic_aggregation_result_model_json2 = query_topic_aggregation_result_model.to_dict() assert query_topic_aggregation_result_model_json2 == query_topic_aggregation_result_model_json -class TestModel_QueryTrendAggregationResult(): + +class TestModel_QueryTrendAggregationResult: """ Test Class for QueryTrendAggregationResult """ @@ -7950,7 +8340,7 @@ def test_query_trend_aggregation_result_serialization(self): # Construct a json representation of a QueryTrendAggregationResult model query_trend_aggregation_result_model_json = {} - query_trend_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_trend_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation query_trend_aggregation_result_model = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json) @@ -7967,7 +8357,8 @@ def test_query_trend_aggregation_result_serialization(self): query_trend_aggregation_result_model_json2 = query_trend_aggregation_result_model.to_dict() assert query_trend_aggregation_result_model_json2 == query_trend_aggregation_result_model_json -class TestModel_ResultPassageAnswer(): + +class TestModel_ResultPassageAnswer: """ Test Class for ResultPassageAnswer """ @@ -7999,7 +8390,8 @@ def test_result_passage_answer_serialization(self): result_passage_answer_model_json2 = result_passage_answer_model.to_dict() assert result_passage_answer_model_json2 == result_passage_answer_model_json -class TestModel_RetrievalDetails(): + +class TestModel_RetrievalDetails: """ Test Class for RetrievalDetails """ @@ -8028,7 +8420,8 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestModel_StopWordList(): + +class TestModel_StopWordList: """ Test Class for StopWordList """ @@ -8057,7 +8450,8 @@ def test_stop_word_list_serialization(self): stop_word_list_model_json2 = stop_word_list_model.to_dict() assert stop_word_list_model_json2 == stop_word_list_model_json -class TestModel_TableBodyCells(): + +class TestModel_TableBodyCells: """ Test Class for TableBodyCells """ @@ -8069,29 +8463,11 @@ def test_table_body_cells_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model @@ -8105,12 +8481,12 @@ def test_table_body_cells_serialization(self): table_body_cells_model_json['row_index_end'] = 26 table_body_cells_model_json['column_index_begin'] = 26 table_body_cells_model_json['column_index_end'] = 26 - table_body_cells_model_json['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model_json['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model_json['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model_json['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model_json['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model_json['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model_json['row_header_ids'] = ['testString'] + table_body_cells_model_json['row_header_texts'] = ['testString'] + table_body_cells_model_json['row_header_texts_normalized'] = ['testString'] + table_body_cells_model_json['column_header_ids'] = ['testString'] + table_body_cells_model_json['column_header_texts'] = ['testString'] + table_body_cells_model_json['column_header_texts_normalized'] = ['testString'] table_body_cells_model_json['attributes'] = [document_attribute_model] # Construct a model instance of TableBodyCells by calling from_dict on the json representation @@ -8128,7 +8504,8 @@ def test_table_body_cells_serialization(self): table_body_cells_model_json2 = table_body_cells_model.to_dict() assert table_body_cells_model_json2 == table_body_cells_model_json -class TestModel_TableCellKey(): + +class TestModel_TableCellKey: """ Test Class for TableCellKey """ @@ -8140,7 +8517,7 @@ def test_table_cell_key_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8165,7 +8542,8 @@ def test_table_cell_key_serialization(self): table_cell_key_model_json2 = table_cell_key_model.to_dict() assert table_cell_key_model_json2 == table_cell_key_model_json -class TestModel_TableCellValues(): + +class TestModel_TableCellValues: """ Test Class for TableCellValues """ @@ -8177,7 +8555,7 @@ def test_table_cell_values_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8202,94 +8580,8 @@ def test_table_cell_values_serialization(self): table_cell_values_model_json2 = table_cell_values_model.to_dict() assert table_cell_values_model_json2 == table_cell_values_model_json -class TestModel_TableColumnHeaderIds(): - """ - Test Class for TableColumnHeaderIds - """ - - def test_table_column_header_ids_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderIds - """ - - # Construct a json representation of a TableColumnHeaderIds model - table_column_header_ids_model_json = {} - table_column_header_ids_model_json['id'] = 'testString' - - # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation - table_column_header_ids_model = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json) - assert table_column_header_ids_model != False - - # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation - table_column_header_ids_model_dict = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json).__dict__ - table_column_header_ids_model2 = TableColumnHeaderIds(**table_column_header_ids_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_ids_model == table_column_header_ids_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_ids_model_json2 = table_column_header_ids_model.to_dict() - assert table_column_header_ids_model_json2 == table_column_header_ids_model_json -class TestModel_TableColumnHeaderTexts(): - """ - Test Class for TableColumnHeaderTexts - """ - - def test_table_column_header_texts_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderTexts - """ - - # Construct a json representation of a TableColumnHeaderTexts model - table_column_header_texts_model_json = {} - table_column_header_texts_model_json['text'] = 'testString' - - # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation - table_column_header_texts_model = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json) - assert table_column_header_texts_model != False - - # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation - table_column_header_texts_model_dict = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json).__dict__ - table_column_header_texts_model2 = TableColumnHeaderTexts(**table_column_header_texts_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_texts_model == table_column_header_texts_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_texts_model_json2 = table_column_header_texts_model.to_dict() - assert table_column_header_texts_model_json2 == table_column_header_texts_model_json - -class TestModel_TableColumnHeaderTextsNormalized(): - """ - Test Class for TableColumnHeaderTextsNormalized - """ - - def test_table_column_header_texts_normalized_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderTextsNormalized - """ - - # Construct a json representation of a TableColumnHeaderTextsNormalized model - table_column_header_texts_normalized_model_json = {} - table_column_header_texts_normalized_model_json['text_normalized'] = 'testString' - - # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation - table_column_header_texts_normalized_model = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json) - assert table_column_header_texts_normalized_model != False - - # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation - table_column_header_texts_normalized_model_dict = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json).__dict__ - table_column_header_texts_normalized_model2 = TableColumnHeaderTextsNormalized(**table_column_header_texts_normalized_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_texts_normalized_model == table_column_header_texts_normalized_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_texts_normalized_model_json2 = table_column_header_texts_normalized_model.to_dict() - assert table_column_header_texts_normalized_model_json2 == table_column_header_texts_normalized_model_json - -class TestModel_TableColumnHeaders(): +class TestModel_TableColumnHeaders: """ Test Class for TableColumnHeaders """ @@ -8299,10 +8591,16 @@ def test_table_column_headers_serialization(self): Test serialization/deserialization for TableColumnHeaders """ + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + # Construct a json representation of a TableColumnHeaders model table_column_headers_model_json = {} table_column_headers_model_json['cell_id'] = 'testString' - table_column_headers_model_json['location'] = {'foo': 'bar'} + table_column_headers_model_json['location'] = table_element_location_model table_column_headers_model_json['text'] = 'testString' table_column_headers_model_json['text_normalized'] = 'testString' table_column_headers_model_json['row_index_begin'] = 26 @@ -8325,7 +8623,8 @@ def test_table_column_headers_serialization(self): table_column_headers_model_json2 = table_column_headers_model.to_dict() assert table_column_headers_model_json2 == table_column_headers_model_json -class TestModel_TableElementLocation(): + +class TestModel_TableElementLocation: """ Test Class for TableElementLocation """ @@ -8355,7 +8654,8 @@ def test_table_element_location_serialization(self): table_element_location_model_json2 = table_element_location_model.to_dict() assert table_element_location_model_json2 == table_element_location_model_json -class TestModel_TableHeaders(): + +class TestModel_TableHeaders: """ Test Class for TableHeaders """ @@ -8365,10 +8665,16 @@ def test_table_headers_serialization(self): Test serialization/deserialization for TableHeaders """ + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + # Construct a json representation of a TableHeaders model table_headers_model_json = {} table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = {'foo': 'bar'} + table_headers_model_json['location'] = table_element_location_model table_headers_model_json['text'] = 'testString' table_headers_model_json['row_index_begin'] = 26 table_headers_model_json['row_index_end'] = 26 @@ -8390,7 +8696,8 @@ def test_table_headers_serialization(self): table_headers_model_json2 = table_headers_model.to_dict() assert table_headers_model_json2 == table_headers_model_json -class TestModel_TableKeyValuePairs(): + +class TestModel_TableKeyValuePairs: """ Test Class for TableKeyValuePairs """ @@ -8402,16 +8709,16 @@ def test_table_key_value_pairs_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' @@ -8436,7 +8743,8 @@ def test_table_key_value_pairs_serialization(self): table_key_value_pairs_model_json2 = table_key_value_pairs_model.to_dict() assert table_key_value_pairs_model_json2 == table_key_value_pairs_model_json -class TestModel_TableResultTable(): + +class TestModel_TableResultTable: """ Test Class for TableResultTable """ @@ -8448,24 +8756,24 @@ def test_table_result_table_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -8475,9 +8783,9 @@ def test_table_result_table_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -8485,44 +8793,26 @@ def test_table_result_table_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -8530,12 +8820,12 @@ def test_table_result_table_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] # Construct a json representation of a TableResultTable model @@ -8566,94 +8856,8 @@ def test_table_result_table_serialization(self): table_result_table_model_json2 = table_result_table_model.to_dict() assert table_result_table_model_json2 == table_result_table_model_json -class TestModel_TableRowHeaderIds(): - """ - Test Class for TableRowHeaderIds - """ - - def test_table_row_header_ids_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderIds - """ - - # Construct a json representation of a TableRowHeaderIds model - table_row_header_ids_model_json = {} - table_row_header_ids_model_json['id'] = 'testString' - - # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation - table_row_header_ids_model = TableRowHeaderIds.from_dict(table_row_header_ids_model_json) - assert table_row_header_ids_model != False - - # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation - table_row_header_ids_model_dict = TableRowHeaderIds.from_dict(table_row_header_ids_model_json).__dict__ - table_row_header_ids_model2 = TableRowHeaderIds(**table_row_header_ids_model_dict) - - # Verify the model instances are equivalent - assert table_row_header_ids_model == table_row_header_ids_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_ids_model_json2 = table_row_header_ids_model.to_dict() - assert table_row_header_ids_model_json2 == table_row_header_ids_model_json - -class TestModel_TableRowHeaderTexts(): - """ - Test Class for TableRowHeaderTexts - """ - - def test_table_row_header_texts_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderTexts - """ - - # Construct a json representation of a TableRowHeaderTexts model - table_row_header_texts_model_json = {} - table_row_header_texts_model_json['text'] = 'testString' - - # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation - table_row_header_texts_model = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json) - assert table_row_header_texts_model != False - - # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation - table_row_header_texts_model_dict = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json).__dict__ - table_row_header_texts_model2 = TableRowHeaderTexts(**table_row_header_texts_model_dict) - - # Verify the model instances are equivalent - assert table_row_header_texts_model == table_row_header_texts_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_texts_model_json2 = table_row_header_texts_model.to_dict() - assert table_row_header_texts_model_json2 == table_row_header_texts_model_json - -class TestModel_TableRowHeaderTextsNormalized(): - """ - Test Class for TableRowHeaderTextsNormalized - """ - - def test_table_row_header_texts_normalized_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderTextsNormalized - """ - - # Construct a json representation of a TableRowHeaderTextsNormalized model - table_row_header_texts_normalized_model_json = {} - table_row_header_texts_normalized_model_json['text_normalized'] = 'testString' - - # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation - table_row_header_texts_normalized_model = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json) - assert table_row_header_texts_normalized_model != False - - # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation - table_row_header_texts_normalized_model_dict = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json).__dict__ - table_row_header_texts_normalized_model2 = TableRowHeaderTextsNormalized(**table_row_header_texts_normalized_model_dict) - # Verify the model instances are equivalent - assert table_row_header_texts_normalized_model == table_row_header_texts_normalized_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_texts_normalized_model_json2 = table_row_header_texts_normalized_model.to_dict() - assert table_row_header_texts_normalized_model_json2 == table_row_header_texts_normalized_model_json - -class TestModel_TableRowHeaders(): +class TestModel_TableRowHeaders: """ Test Class for TableRowHeaders """ @@ -8665,7 +8869,7 @@ def test_table_row_headers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8695,7 +8899,8 @@ def test_table_row_headers_serialization(self): table_row_headers_model_json2 = table_row_headers_model.to_dict() assert table_row_headers_model_json2 == table_row_headers_model_json -class TestModel_TableTextLocation(): + +class TestModel_TableTextLocation: """ Test Class for TableTextLocation """ @@ -8707,7 +8912,7 @@ def test_table_text_location_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8731,7 +8936,8 @@ def test_table_text_location_serialization(self): table_text_location_model_json2 = table_text_location_model.to_dict() assert table_text_location_model_json2 == table_text_location_model_json -class TestModel_TrainingExample(): + +class TestModel_TrainingExample: """ Test Class for TrainingExample """ @@ -8762,7 +8968,8 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestModel_TrainingQuery(): + +class TestModel_TrainingQuery: """ Test Class for TrainingQuery """ @@ -8774,7 +8981,7 @@ def test_training_query_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 @@ -8800,7 +9007,8 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestModel_TrainingQuerySet(): + +class TestModel_TrainingQuerySet: """ Test Class for TrainingQuerySet """ @@ -8812,12 +9020,12 @@ def test_training_query_set_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_query_model = {} # TrainingQuery + training_query_model = {} # TrainingQuery training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' training_query_model['examples'] = [training_example_model] @@ -8841,7 +9049,8 @@ def test_training_query_set_serialization(self): training_query_set_model_json2 = training_query_set_model.to_dict() assert training_query_set_model_json2 == training_query_set_model_json -class TestModel_UpdateDocumentClassifier(): + +class TestModel_UpdateDocumentClassifier: """ Test Class for UpdateDocumentClassifier """ @@ -8871,7 +9080,39 @@ def test_update_document_classifier_serialization(self): update_document_classifier_model_json2 = update_document_classifier_model.to_dict() assert update_document_classifier_model_json2 == update_document_classifier_model_json -class TestModel_QueryAggregationQueryCalculationAggregation(): + +class TestModel_WebhookHeader: + """ + Test Class for WebhookHeader + """ + + def test_webhook_header_serialization(self): + """ + Test serialization/deserialization for WebhookHeader + """ + + # Construct a json representation of a WebhookHeader model + webhook_header_model_json = {} + webhook_header_model_json['name'] = 'testString' + webhook_header_model_json['value'] = 'testString' + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model = WebhookHeader.from_dict(webhook_header_model_json) + assert webhook_header_model != False + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model_dict = WebhookHeader.from_dict(webhook_header_model_json).__dict__ + webhook_header_model2 = WebhookHeader(**webhook_header_model_dict) + + # Verify the model instances are equivalent + assert webhook_header_model == webhook_header_model2 + + # Convert model instance back to dict and verify no loss of data + webhook_header_model_json2 = webhook_header_model.to_dict() + assert webhook_header_model_json2 == webhook_header_model_json + + +class TestModel_QueryAggregationQueryCalculationAggregation: """ Test Class for QueryAggregationQueryCalculationAggregation """ @@ -8902,7 +9143,8 @@ def test_query_aggregation_query_calculation_aggregation_serialization(self): query_aggregation_query_calculation_aggregation_model_json2 = query_aggregation_query_calculation_aggregation_model.to_dict() assert query_aggregation_query_calculation_aggregation_model_json2 == query_aggregation_query_calculation_aggregation_model_json -class TestModel_QueryAggregationQueryFilterAggregation(): + +class TestModel_QueryAggregationQueryFilterAggregation: """ Test Class for QueryAggregationQueryFilterAggregation """ @@ -8917,7 +9159,7 @@ def test_query_aggregation_query_filter_aggregation_serialization(self): query_aggregation_query_filter_aggregation_model_json['type'] = 'filter' query_aggregation_query_filter_aggregation_model_json['match'] = 'testString' query_aggregation_query_filter_aggregation_model_json['matching_results'] = 26 - query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] + query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation query_aggregation_query_filter_aggregation_model = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json) @@ -8934,7 +9176,8 @@ def test_query_aggregation_query_filter_aggregation_serialization(self): query_aggregation_query_filter_aggregation_model_json2 = query_aggregation_query_filter_aggregation_model.to_dict() assert query_aggregation_query_filter_aggregation_model_json2 == query_aggregation_query_filter_aggregation_model_json -class TestModel_QueryAggregationQueryGroupByAggregation(): + +class TestModel_QueryAggregationQueryGroupByAggregation: """ Test Class for QueryAggregationQueryGroupByAggregation """ @@ -8946,13 +9189,13 @@ def test_query_aggregation_query_group_by_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult + query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult query_group_by_aggregation_result_model['key'] = 'testString' query_group_by_aggregation_result_model['matching_results'] = 38 query_group_by_aggregation_result_model['relevancy'] = 72.5 query_group_by_aggregation_result_model['total_matching_documents'] = 38 query_group_by_aggregation_result_model['estimated_matching_results'] = 72.5 - query_group_by_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_group_by_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryGroupByAggregation model query_aggregation_query_group_by_aggregation_model_json = {} @@ -8974,7 +9217,8 @@ def test_query_aggregation_query_group_by_aggregation_serialization(self): query_aggregation_query_group_by_aggregation_model_json2 = query_aggregation_query_group_by_aggregation_model.to_dict() assert query_aggregation_query_group_by_aggregation_model_json2 == query_aggregation_query_group_by_aggregation_model_json -class TestModel_QueryAggregationQueryHistogramAggregation(): + +class TestModel_QueryAggregationQueryHistogramAggregation: """ Test Class for QueryAggregationQueryHistogramAggregation """ @@ -8986,10 +9230,10 @@ def test_query_aggregation_query_histogram_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult + query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult query_histogram_aggregation_result_model['key'] = 26 query_histogram_aggregation_result_model['matching_results'] = 38 - query_histogram_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_histogram_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryHistogramAggregation model query_aggregation_query_histogram_aggregation_model_json = {} @@ -9014,7 +9258,8 @@ def test_query_aggregation_query_histogram_aggregation_serialization(self): query_aggregation_query_histogram_aggregation_model_json2 = query_aggregation_query_histogram_aggregation_model.to_dict() assert query_aggregation_query_histogram_aggregation_model_json2 == query_aggregation_query_histogram_aggregation_model_json -class TestModel_QueryAggregationQueryNestedAggregation(): + +class TestModel_QueryAggregationQueryNestedAggregation: """ Test Class for QueryAggregationQueryNestedAggregation """ @@ -9029,7 +9274,7 @@ def test_query_aggregation_query_nested_aggregation_serialization(self): query_aggregation_query_nested_aggregation_model_json['type'] = 'nested' query_aggregation_query_nested_aggregation_model_json['path'] = 'testString' query_aggregation_query_nested_aggregation_model_json['matching_results'] = 26 - query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] + query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation query_aggregation_query_nested_aggregation_model = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json) @@ -9046,7 +9291,8 @@ def test_query_aggregation_query_nested_aggregation_serialization(self): query_aggregation_query_nested_aggregation_model_json2 = query_aggregation_query_nested_aggregation_model.to_dict() assert query_aggregation_query_nested_aggregation_model_json2 == query_aggregation_query_nested_aggregation_model_json -class TestModel_QueryAggregationQueryPairAggregation(): + +class TestModel_QueryAggregationQueryPairAggregation: """ Test Class for QueryAggregationQueryPairAggregation """ @@ -9058,8 +9304,8 @@ def test_query_aggregation_query_pair_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_pair_aggregation_result_model = {} # QueryPairAggregationResult - query_pair_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_pair_aggregation_result_model = {} # QueryPairAggregationResult + query_pair_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryPairAggregation model query_aggregation_query_pair_aggregation_model_json = {} @@ -9085,7 +9331,8 @@ def test_query_aggregation_query_pair_aggregation_serialization(self): query_aggregation_query_pair_aggregation_model_json2 = query_aggregation_query_pair_aggregation_model.to_dict() assert query_aggregation_query_pair_aggregation_model_json2 == query_aggregation_query_pair_aggregation_model_json -class TestModel_QueryAggregationQueryTermAggregation(): + +class TestModel_QueryAggregationQueryTermAggregation: """ Test Class for QueryAggregationQueryTermAggregation """ @@ -9097,13 +9344,13 @@ def test_query_aggregation_query_term_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model = {} # QueryTermAggregationResult query_term_aggregation_result_model['key'] = 'testString' query_term_aggregation_result_model['matching_results'] = 38 query_term_aggregation_result_model['relevancy'] = 72.5 query_term_aggregation_result_model['total_matching_documents'] = 38 query_term_aggregation_result_model['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTermAggregation model query_aggregation_query_term_aggregation_model_json = {} @@ -9128,7 +9375,8 @@ def test_query_aggregation_query_term_aggregation_serialization(self): query_aggregation_query_term_aggregation_model_json2 = query_aggregation_query_term_aggregation_model.to_dict() assert query_aggregation_query_term_aggregation_model_json2 == query_aggregation_query_term_aggregation_model_json -class TestModel_QueryAggregationQueryTimesliceAggregation(): + +class TestModel_QueryAggregationQueryTimesliceAggregation: """ Test Class for QueryAggregationQueryTimesliceAggregation """ @@ -9140,11 +9388,11 @@ def test_query_aggregation_query_timeslice_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult + query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult query_timeslice_aggregation_result_model['key_as_string'] = 'testString' query_timeslice_aggregation_result_model['key'] = 26 query_timeslice_aggregation_result_model['matching_results'] = 26 - query_timeslice_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_timeslice_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTimesliceAggregation model query_aggregation_query_timeslice_aggregation_model_json = {} @@ -9169,7 +9417,8 @@ def test_query_aggregation_query_timeslice_aggregation_serialization(self): query_aggregation_query_timeslice_aggregation_model_json2 = query_aggregation_query_timeslice_aggregation_model.to_dict() assert query_aggregation_query_timeslice_aggregation_model_json2 == query_aggregation_query_timeslice_aggregation_model_json -class TestModel_QueryAggregationQueryTopHitsAggregation(): + +class TestModel_QueryAggregationQueryTopHitsAggregation: """ Test Class for QueryAggregationQueryTopHitsAggregation """ @@ -9181,9 +9430,9 @@ def test_query_aggregation_query_top_hits_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTopHitsAggregation model query_aggregation_query_top_hits_aggregation_model_json = {} @@ -9207,7 +9456,8 @@ def test_query_aggregation_query_top_hits_aggregation_serialization(self): query_aggregation_query_top_hits_aggregation_model_json2 = query_aggregation_query_top_hits_aggregation_model.to_dict() assert query_aggregation_query_top_hits_aggregation_model_json2 == query_aggregation_query_top_hits_aggregation_model_json -class TestModel_QueryAggregationQueryTopicAggregation(): + +class TestModel_QueryAggregationQueryTopicAggregation: """ Test Class for QueryAggregationQueryTopicAggregation """ @@ -9219,8 +9469,8 @@ def test_query_aggregation_query_topic_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_topic_aggregation_result_model = {} # QueryTopicAggregationResult - query_topic_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_topic_aggregation_result_model = {} # QueryTopicAggregationResult + query_topic_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTopicAggregation model query_aggregation_query_topic_aggregation_model_json = {} @@ -9246,7 +9496,8 @@ def test_query_aggregation_query_topic_aggregation_serialization(self): query_aggregation_query_topic_aggregation_model_json2 = query_aggregation_query_topic_aggregation_model.to_dict() assert query_aggregation_query_topic_aggregation_model_json2 == query_aggregation_query_topic_aggregation_model_json -class TestModel_QueryAggregationQueryTrendAggregation(): + +class TestModel_QueryAggregationQueryTrendAggregation: """ Test Class for QueryAggregationQueryTrendAggregation """ @@ -9258,8 +9509,8 @@ def test_query_aggregation_query_trend_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_trend_aggregation_result_model = {} # QueryTrendAggregationResult - query_trend_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_trend_aggregation_result_model = {} # QueryTrendAggregationResult + query_trend_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTrendAggregation model query_aggregation_query_trend_aggregation_model_json = {} diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index fdb19dd0..2fe38ed4 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2023. +# (C) Copyright IBM Corp. 2018, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListLanguages(): + +class TestListLanguages: """ Test Class for list_languages """ @@ -86,16 +86,17 @@ def test_list_languages_all_params(self): # Set up mock url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_languages() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -117,17 +118,19 @@ def test_list_languages_value_error(self): # Set up mock url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_languages(**req_copy) @@ -140,6 +143,7 @@ def test_list_languages_value_error_with_retries(self): _service.disable_retries() self.test_list_languages_value_error() + # endregion ############################################################################## # End of Service: Languages @@ -150,7 +154,8 @@ def test_list_languages_value_error_with_retries(self): ############################################################################## # region -class TestTranslate(): + +class TestTranslate: """ Test Class for translate """ @@ -163,11 +168,13 @@ def test_translate_all_params(self): # Set up mock url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = ['testString'] @@ -181,7 +188,7 @@ def test_translate_all_params(self): model_id=model_id, source=source, target=target, - headers={} + headers={}, ) # Check for correct operation @@ -211,11 +218,13 @@ def test_translate_value_error(self): # Set up mock url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = ['testString'] @@ -228,7 +237,7 @@ def test_translate_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.translate(**req_copy) @@ -241,6 +250,7 @@ def test_translate_value_error_with_retries(self): _service.disable_retries() self.test_translate_value_error() + # endregion ############################################################################## # End of Service: Translation @@ -251,7 +261,8 @@ def test_translate_value_error_with_retries(self): ############################################################################## # region -class TestListIdentifiableLanguages(): + +class TestListIdentifiableLanguages: """ Test Class for list_identifiable_languages """ @@ -264,16 +275,17 @@ def test_list_identifiable_languages_all_params(self): # Set up mock url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_identifiable_languages() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -295,17 +307,19 @@ def test_list_identifiable_languages_value_error(self): # Set up mock url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_identifiable_languages(**req_copy) @@ -318,7 +332,8 @@ def test_list_identifiable_languages_value_error_with_retries(self): _service.disable_retries() self.test_list_identifiable_languages_value_error() -class TestIdentify(): + +class TestIdentify: """ Test Class for identify """ @@ -331,11 +346,13 @@ def test_identify_all_params(self): # Set up mock url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -343,7 +360,7 @@ def test_identify_all_params(self): # Invoke method response = _service.identify( text, - headers={} + headers={}, ) # Check for correct operation @@ -369,11 +386,13 @@ def test_identify_value_error(self): # Set up mock url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -383,7 +402,7 @@ def test_identify_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.identify(**req_copy) @@ -396,6 +415,7 @@ def test_identify_value_error_with_retries(self): _service.disable_retries() self.test_identify_value_error() + # endregion ############################################################################## # End of Service: Identification @@ -406,7 +426,8 @@ def test_identify_value_error_with_retries(self): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -419,11 +440,13 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values source = 'testString' @@ -435,14 +458,14 @@ def test_list_models_all_params(self): source=source, target=target, default=default, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'source={}'.format(source) in query_string assert 'target={}'.format(target) in query_string @@ -465,16 +488,17 @@ def test_list_models_required_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -496,17 +520,19 @@ def test_list_models_value_error(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_models(**req_copy) @@ -519,7 +545,8 @@ def test_list_models_value_error_with_retries(self): _service.disable_retries() self.test_list_models_value_error() -class TestCreateModel(): + +class TestCreateModel: """ Test Class for create_model """ @@ -532,11 +559,13 @@ def test_create_model_all_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -554,14 +583,14 @@ def test_create_model_all_params(self): parallel_corpus=parallel_corpus, parallel_corpus_content_type=parallel_corpus_content_type, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'base_model_id={}'.format(base_model_id) in query_string assert 'name={}'.format(name) in query_string @@ -583,11 +612,13 @@ def test_create_model_required_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -595,14 +626,14 @@ def test_create_model_required_params(self): # Invoke method response = _service.create_model( base_model_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'base_model_id={}'.format(base_model_id) in query_string @@ -623,11 +654,13 @@ def test_create_model_value_error(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -637,7 +670,7 @@ def test_create_model_value_error(self): "base_model_id": base_model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_model(**req_copy) @@ -650,7 +683,8 @@ def test_create_model_value_error_with_retries(self): _service.disable_retries() self.test_create_model_value_error() -class TestDeleteModel(): + +class TestDeleteModel: """ Test Class for delete_model """ @@ -663,11 +697,13 @@ def test_delete_model_all_params(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -675,7 +711,7 @@ def test_delete_model_all_params(self): # Invoke method response = _service.delete_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -699,11 +735,13 @@ def test_delete_model_value_error(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -713,7 +751,7 @@ def test_delete_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_model(**req_copy) @@ -726,7 +764,8 @@ def test_delete_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_model_value_error() -class TestGetModel(): + +class TestGetModel: """ Test Class for get_model """ @@ -739,11 +778,13 @@ def test_get_model_all_params(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -751,7 +792,7 @@ def test_get_model_all_params(self): # Invoke method response = _service.get_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -775,11 +816,13 @@ def test_get_model_value_error(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -789,7 +832,7 @@ def test_get_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_model(**req_copy) @@ -802,6 +845,7 @@ def test_get_model_value_error_with_retries(self): _service.disable_retries() self.test_get_model_value_error() + # endregion ############################################################################## # End of Service: Models @@ -812,7 +856,8 @@ def test_get_model_value_error_with_retries(self): ############################################################################## # region -class TestListDocuments(): + +class TestListDocuments: """ Test Class for list_documents """ @@ -825,16 +870,17 @@ def test_list_documents_all_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_documents() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -856,17 +902,19 @@ def test_list_documents_value_error(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_documents(**req_copy) @@ -879,7 +927,8 @@ def test_list_documents_value_error_with_retries(self): _service.disable_retries() self.test_list_documents_value_error() -class TestTranslateDocument(): + +class TestTranslateDocument: """ Test Class for translate_document """ @@ -892,11 +941,13 @@ def test_translate_document_all_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -916,7 +967,7 @@ def test_translate_document_all_params(self): source=source, target=target, document_id=document_id, - headers={} + headers={}, ) # Check for correct operation @@ -940,11 +991,13 @@ def test_translate_document_required_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -954,7 +1007,7 @@ def test_translate_document_required_params(self): response = _service.translate_document( file, filename=filename, - headers={} + headers={}, ) # Check for correct operation @@ -978,11 +1031,13 @@ def test_translate_document_value_error(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -993,7 +1048,7 @@ def test_translate_document_value_error(self): "file": file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.translate_document(**req_copy) @@ -1006,7 +1061,8 @@ def test_translate_document_value_error_with_retries(self): _service.disable_retries() self.test_translate_document_value_error() -class TestGetDocumentStatus(): + +class TestGetDocumentStatus: """ Test Class for get_document_status """ @@ -1019,11 +1075,13 @@ def test_get_document_status_all_params(self): # Set up mock url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1031,7 +1089,7 @@ def test_get_document_status_all_params(self): # Invoke method response = _service.get_document_status( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1055,11 +1113,13 @@ def test_get_document_status_value_error(self): # Set up mock url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1069,7 +1129,7 @@ def test_get_document_status_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_status(**req_copy) @@ -1082,7 +1142,8 @@ def test_get_document_status_value_error_with_retries(self): _service.disable_retries() self.test_get_document_status_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -1094,9 +1155,11 @@ def test_delete_document_all_params(self): """ # Set up mock url = preprocess_url('/v3/documents/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values document_id = 'testString' @@ -1104,7 +1167,7 @@ def test_delete_document_all_params(self): # Invoke method response = _service.delete_document( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1127,9 +1190,11 @@ def test_delete_document_value_error(self): """ # Set up mock url = preprocess_url('/v3/documents/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values document_id = 'testString' @@ -1139,7 +1204,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -1152,7 +1217,8 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() -class TestGetTranslatedDocument(): + +class TestGetTranslatedDocument: """ Test Class for get_translated_document """ @@ -1165,11 +1231,13 @@ def test_get_translated_document_all_params(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1179,7 +1247,7 @@ def test_get_translated_document_all_params(self): response = _service.get_translated_document( document_id, accept=accept, - headers={} + headers={}, ) # Check for correct operation @@ -1203,11 +1271,13 @@ def test_get_translated_document_required_params(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1215,7 +1285,7 @@ def test_get_translated_document_required_params(self): # Invoke method response = _service.get_translated_document( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1239,11 +1309,13 @@ def test_get_translated_document_value_error(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1253,7 +1325,7 @@ def test_get_translated_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_translated_document(**req_copy) @@ -1266,6 +1338,7 @@ def test_get_translated_document_value_error_with_retries(self): _service.disable_retries() self.test_get_translated_document_value_error() + # endregion ############################################################################## # End of Service: DocumentTranslation @@ -1276,7 +1349,9 @@ def test_get_translated_document_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_DeleteModelResult(): + + +class TestModel_DeleteModelResult: """ Test Class for DeleteModelResult """ @@ -1305,7 +1380,8 @@ def test_delete_model_result_serialization(self): delete_model_result_model_json2 = delete_model_result_model.to_dict() assert delete_model_result_model_json2 == delete_model_result_model_json -class TestModel_DocumentList(): + +class TestModel_DocumentList: """ Test Class for DocumentList """ @@ -1317,7 +1393,7 @@ def test_document_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_status_model = {} # DocumentStatus + document_status_model = {} # DocumentStatus document_status_model['document_id'] = 'testString' document_status_model['filename'] = 'testString' document_status_model['status'] = 'processing' @@ -1350,7 +1426,8 @@ def test_document_list_serialization(self): document_list_model_json2 = document_list_model.to_dict() assert document_list_model_json2 == document_list_model_json -class TestModel_DocumentStatus(): + +class TestModel_DocumentStatus: """ Test Class for DocumentStatus """ @@ -1390,7 +1467,8 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestModel_IdentifiableLanguage(): + +class TestModel_IdentifiableLanguage: """ Test Class for IdentifiableLanguage """ @@ -1420,7 +1498,8 @@ def test_identifiable_language_serialization(self): identifiable_language_model_json2 = identifiable_language_model.to_dict() assert identifiable_language_model_json2 == identifiable_language_model_json -class TestModel_IdentifiableLanguages(): + +class TestModel_IdentifiableLanguages: """ Test Class for IdentifiableLanguages """ @@ -1432,7 +1511,7 @@ def test_identifiable_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - identifiable_language_model = {} # IdentifiableLanguage + identifiable_language_model = {} # IdentifiableLanguage identifiable_language_model['language'] = 'testString' identifiable_language_model['name'] = 'testString' @@ -1455,7 +1534,8 @@ def test_identifiable_languages_serialization(self): identifiable_languages_model_json2 = identifiable_languages_model.to_dict() assert identifiable_languages_model_json2 == identifiable_languages_model_json -class TestModel_IdentifiedLanguage(): + +class TestModel_IdentifiedLanguage: """ Test Class for IdentifiedLanguage """ @@ -1485,7 +1565,8 @@ def test_identified_language_serialization(self): identified_language_model_json2 = identified_language_model.to_dict() assert identified_language_model_json2 == identified_language_model_json -class TestModel_IdentifiedLanguages(): + +class TestModel_IdentifiedLanguages: """ Test Class for IdentifiedLanguages """ @@ -1497,7 +1578,7 @@ def test_identified_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - identified_language_model = {} # IdentifiedLanguage + identified_language_model = {} # IdentifiedLanguage identified_language_model['language'] = 'testString' identified_language_model['confidence'] = 0 @@ -1520,7 +1601,8 @@ def test_identified_languages_serialization(self): identified_languages_model_json2 = identified_languages_model.to_dict() assert identified_languages_model_json2 == identified_languages_model_json -class TestModel_Language(): + +class TestModel_Language: """ Test Class for Language """ @@ -1557,7 +1639,8 @@ def test_language_serialization(self): language_model_json2 = language_model.to_dict() assert language_model_json2 == language_model_json -class TestModel_Languages(): + +class TestModel_Languages: """ Test Class for Languages """ @@ -1569,7 +1652,7 @@ def test_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - language_model = {} # Language + language_model = {} # Language language_model['language'] = 'testString' language_model['language_name'] = 'testString' language_model['native_language_name'] = 'testString' @@ -1599,7 +1682,8 @@ def test_languages_serialization(self): languages_model_json2 = languages_model.to_dict() assert languages_model_json2 == languages_model_json -class TestModel_Translation(): + +class TestModel_Translation: """ Test Class for Translation """ @@ -1628,7 +1712,8 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestModel_TranslationModel(): + +class TestModel_TranslationModel: """ Test Class for TranslationModel """ @@ -1666,7 +1751,8 @@ def test_translation_model_serialization(self): translation_model_model_json2 = translation_model_model.to_dict() assert translation_model_model_json2 == translation_model_model_json -class TestModel_TranslationModels(): + +class TestModel_TranslationModels: """ Test Class for TranslationModels """ @@ -1678,7 +1764,7 @@ def test_translation_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - translation_model_model = {} # TranslationModel + translation_model_model = {} # TranslationModel translation_model_model['model_id'] = 'testString' translation_model_model['name'] = 'testString' translation_model_model['source'] = 'testString' @@ -1709,7 +1795,8 @@ def test_translation_models_serialization(self): translation_models_model_json2 = translation_models_model.to_dict() assert translation_models_model_json2 == translation_models_model_json -class TestModel_TranslationResult(): + +class TestModel_TranslationResult: """ Test Class for TranslationResult """ @@ -1721,7 +1808,7 @@ def test_translation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - translation_model = {} # Translation + translation_model = {} # Translation translation_model['translation'] = 'testString' # Construct a json representation of a TranslationResult model diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 54708297..b79c21c4 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestAnalyze(): + +class TestAnalyze: """ Test Class for analyze """ @@ -86,11 +86,13 @@ def test_analyze_all_params(self): # Set up mock url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} @@ -98,7 +100,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} - concepts_options_model['limit'] = 50 + concepts_options_model['limit'] = 8 # Construct a dict representation of a EmotionOptions model emotion_options_model = {} @@ -107,7 +109,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} - entities_options_model['limit'] = 250 + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False @@ -115,7 +117,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} - keywords_options_model['limit'] = 250 + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False @@ -125,7 +127,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False @@ -136,12 +138,12 @@ def test_analyze_all_params(self): # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} - summarization_options_model['limit'] = 10 + summarization_options_model['limit'] = 3 # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' # Construct a dict representation of a SyntaxOptionsTokens model @@ -161,7 +163,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'foo': 'bar'} + features_model['metadata'] = {'anyKey': 'anyValue'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -193,7 +195,7 @@ def test_analyze_all_params(self): return_analyzed_text=return_analyzed_text, language=language, limit_text_characters=limit_text_characters, - headers={} + headers={}, ) # Check for correct operation @@ -229,11 +231,13 @@ def test_analyze_value_error(self): # Set up mock url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} @@ -241,7 +245,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} - concepts_options_model['limit'] = 50 + concepts_options_model['limit'] = 8 # Construct a dict representation of a EmotionOptions model emotion_options_model = {} @@ -250,7 +254,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} - entities_options_model['limit'] = 250 + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False @@ -258,7 +262,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} - keywords_options_model['limit'] = 250 + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False @@ -268,7 +272,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False @@ -279,12 +283,12 @@ def test_analyze_value_error(self): # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} - summarization_options_model['limit'] = 10 + summarization_options_model['limit'] = 3 # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' # Construct a dict representation of a SyntaxOptionsTokens model @@ -304,7 +308,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'foo': 'bar'} + features_model['metadata'] = {'anyKey': 'anyValue'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -329,7 +333,7 @@ def test_analyze_value_error(self): "features": features, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.analyze(**req_copy) @@ -342,6 +346,7 @@ def test_analyze_value_error_with_retries(self): _service.disable_retries() self.test_analyze_value_error() + # endregion ############################################################################## # End of Service: Analyze @@ -352,7 +357,8 @@ def test_analyze_value_error_with_retries(self): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -365,16 +371,17 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -396,17 +403,19 @@ def test_list_models_value_error(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_models(**req_copy) @@ -419,7 +428,8 @@ def test_list_models_value_error_with_retries(self): _service.disable_retries() self.test_list_models_value_error() -class TestDeleteModel(): + +class TestDeleteModel: """ Test Class for delete_model """ @@ -432,11 +442,13 @@ def test_delete_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -444,7 +456,7 @@ def test_delete_model_all_params(self): # Invoke method response = _service.delete_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -468,11 +480,13 @@ def test_delete_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -482,7 +496,7 @@ def test_delete_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_model(**req_copy) @@ -495,6 +509,7 @@ def test_delete_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_model_value_error() + # endregion ############################################################################## # End of Service: ManageModels @@ -505,7 +520,8 @@ def test_delete_model_value_error_with_retries(self): ############################################################################## # region -class TestCreateCategoriesModel(): + +class TestCreateCategoriesModel: """ Test Class for create_categories_model """ @@ -517,18 +533,21 @@ def test_create_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -540,11 +559,12 @@ def test_create_categories_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, - headers={} + headers={}, ) # Check for correct operation @@ -567,24 +587,24 @@ def test_create_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.create_categories_model( language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -607,26 +627,26 @@ def test_create_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_categories_model(**req_copy) @@ -639,7 +659,8 @@ def test_create_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_create_categories_model_value_error() -class TestListCategoriesModels(): + +class TestListCategoriesModels: """ Test Class for list_categories_models """ @@ -651,17 +672,18 @@ def test_list_categories_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_categories_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -682,18 +704,20 @@ def test_list_categories_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_categories_models(**req_copy) @@ -706,7 +730,8 @@ def test_list_categories_models_value_error_with_retries(self): _service.disable_retries() self.test_list_categories_models_value_error() -class TestGetCategoriesModel(): + +class TestGetCategoriesModel: """ Test Class for get_categories_model """ @@ -718,12 +743,14 @@ def test_get_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -731,7 +758,7 @@ def test_get_categories_model_all_params(self): # Invoke method response = _service.get_categories_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -754,12 +781,14 @@ def test_get_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -769,7 +798,7 @@ def test_get_categories_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_categories_model(**req_copy) @@ -782,7 +811,8 @@ def test_get_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_get_categories_model_value_error() -class TestUpdateCategoriesModel(): + +class TestUpdateCategoriesModel: """ Test Class for update_categories_model """ @@ -794,12 +824,14 @@ def test_update_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -807,6 +839,7 @@ def test_update_categories_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -819,11 +852,12 @@ def test_update_categories_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, - headers={} + headers={}, ) # Check for correct operation @@ -846,26 +880,26 @@ def test_update_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.update_categories_model( model_id, language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -888,28 +922,28 @@ def test_update_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_categories_model(**req_copy) @@ -922,7 +956,8 @@ def test_update_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_update_categories_model_value_error() -class TestDeleteCategoriesModel(): + +class TestDeleteCategoriesModel: """ Test Class for delete_categories_model """ @@ -935,11 +970,13 @@ def test_delete_categories_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -947,7 +984,7 @@ def test_delete_categories_model_all_params(self): # Invoke method response = _service.delete_categories_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -971,11 +1008,13 @@ def test_delete_categories_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -985,7 +1024,7 @@ def test_delete_categories_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_categories_model(**req_copy) @@ -998,6 +1037,7 @@ def test_delete_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_categories_model_value_error() + # endregion ############################################################################## # End of Service: ManageCategoriesModels @@ -1008,7 +1048,8 @@ def test_delete_categories_model_value_error_with_retries(self): ############################################################################## # region -class TestCreateClassificationsModel(): + +class TestCreateClassificationsModel: """ Test Class for create_classifications_model """ @@ -1020,12 +1061,14 @@ def test_create_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a ClassificationsTrainingParameters model classifications_training_parameters_model = {} @@ -1036,6 +1079,7 @@ def test_create_classifications_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -1048,12 +1092,13 @@ def test_create_classifications_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, training_parameters=training_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -1076,24 +1121,24 @@ def test_create_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.create_classifications_model( language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -1116,26 +1161,26 @@ def test_create_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_classifications_model(**req_copy) @@ -1148,7 +1193,8 @@ def test_create_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_create_classifications_model_value_error() -class TestListClassificationsModels(): + +class TestListClassificationsModels: """ Test Class for list_classifications_models """ @@ -1160,17 +1206,18 @@ def test_list_classifications_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_classifications_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1191,18 +1238,20 @@ def test_list_classifications_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_classifications_models(**req_copy) @@ -1215,7 +1264,8 @@ def test_list_classifications_models_value_error_with_retries(self): _service.disable_retries() self.test_list_classifications_models_value_error() -class TestGetClassificationsModel(): + +class TestGetClassificationsModel: """ Test Class for get_classifications_model """ @@ -1227,12 +1277,14 @@ def test_get_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1240,7 +1292,7 @@ def test_get_classifications_model_all_params(self): # Invoke method response = _service.get_classifications_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -1263,12 +1315,14 @@ def test_get_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1278,7 +1332,7 @@ def test_get_classifications_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_classifications_model(**req_copy) @@ -1291,7 +1345,8 @@ def test_get_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_get_classifications_model_value_error() -class TestUpdateClassificationsModel(): + +class TestUpdateClassificationsModel: """ Test Class for update_classifications_model """ @@ -1303,12 +1358,14 @@ def test_update_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsTrainingParameters model classifications_training_parameters_model = {} @@ -1320,6 +1377,7 @@ def test_update_classifications_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -1333,12 +1391,13 @@ def test_update_classifications_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, training_parameters=training_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -1361,26 +1420,26 @@ def test_update_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.update_classifications_model( model_id, language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -1403,28 +1462,28 @@ def test_update_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_classifications_model(**req_copy) @@ -1437,7 +1496,8 @@ def test_update_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_update_classifications_model_value_error() -class TestDeleteClassificationsModel(): + +class TestDeleteClassificationsModel: """ Test Class for delete_classifications_model """ @@ -1450,11 +1510,13 @@ def test_delete_classifications_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1462,7 +1524,7 @@ def test_delete_classifications_model_all_params(self): # Invoke method response = _service.delete_classifications_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -1486,11 +1548,13 @@ def test_delete_classifications_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1500,7 +1564,7 @@ def test_delete_classifications_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_classifications_model(**req_copy) @@ -1513,6 +1577,7 @@ def test_delete_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_classifications_model_value_error() + # endregion ############################################################################## # End of Service: ManageClassificationsModels @@ -1523,7 +1588,9 @@ def test_delete_classifications_model_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AnalysisResults(): + + +class TestModel_AnalysisResults: """ Test Class for AnalysisResults """ @@ -1535,37 +1602,37 @@ def test_analysis_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - analysis_results_usage_model = {} # AnalysisResultsUsage + analysis_results_usage_model = {} # AnalysisResultsUsage analysis_results_usage_model['features'] = 38 analysis_results_usage_model['text_characters'] = 38 analysis_results_usage_model['text_units'] = 38 - concepts_result_model = {} # ConceptsResult + concepts_result_model = {} # ConceptsResult concepts_result_model['text'] = 'Social network service' concepts_result_model['relevance'] = 0.92186 concepts_result_model['dbpedia_resource'] = 'http://dbpedia.org/resource/Social_network_service' - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['location'] = [38] entity_mention_model['confidence'] = 72.5 - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 - disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model = {} # DisambiguationResult disambiguation_result_model['name'] = 'testString' disambiguation_result_model['dbpedia_resource'] = 'testString' disambiguation_result_model['subtype'] = ['testString'] - entities_result_model = {} # EntitiesResult + entities_result_model = {} # EntitiesResult entities_result_model['type'] = 'testString' entities_result_model['text'] = 'Social network service' entities_result_model['relevance'] = 0.92186 @@ -1576,121 +1643,121 @@ def test_analysis_results_serialization(self): entities_result_model['sentiment'] = feature_sentiment_results_model entities_result_model['disambiguation'] = disambiguation_result_model - keywords_result_model = {} # KeywordsResult + keywords_result_model = {} # KeywordsResult keywords_result_model['count'] = 1 keywords_result_model['relevance'] = 0.864624 keywords_result_model['text'] = 'curated online courses' keywords_result_model['emotion'] = emotion_scores_model keywords_result_model['sentiment'] = feature_sentiment_results_model - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' - categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model = {} # CategoriesResultExplanation categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] - categories_result_model = {} # CategoriesResult + categories_result_model = {} # CategoriesResult categories_result_model['label'] = '/technology and computing/computing/computer software and applications' categories_result_model['score'] = 0.594296 categories_result_model['explanation'] = categories_result_explanation_model - classifications_result_model = {} # ClassificationsResult + classifications_result_model = {} # ClassificationsResult classifications_result_model['class_name'] = 'temperature' classifications_result_model['confidence'] = 0.562519 - document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model = {} # DocumentEmotionResults document_emotion_results_model['emotion'] = emotion_scores_model - targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model = {} # TargetedEmotionResults targeted_emotion_results_model['text'] = 'testString' targeted_emotion_results_model['emotion'] = emotion_scores_model - emotion_result_model = {} # EmotionResult + emotion_result_model = {} # EmotionResult emotion_result_model['document'] = document_emotion_results_model emotion_result_model['targets'] = [targeted_emotion_results_model] - author_model = {} # Author + author_model = {} # Author author_model['name'] = 'testString' - feed_model = {} # Feed + feed_model = {} # Feed feed_model['link'] = 'testString' - features_results_metadata_model = {} # FeaturesResultsMetadata + features_results_metadata_model = {} # FeaturesResultsMetadata features_results_metadata_model['authors'] = [author_model] features_results_metadata_model['publication_date'] = 'testString' features_results_metadata_model['title'] = 'testString' features_results_metadata_model['image'] = 'testString' features_results_metadata_model['feeds'] = [feed_model] - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'Best Actor' relation_entity_model['type'] = 'EntertainmentAward' - relation_argument_model = {} # RelationArgument + relation_argument_model = {} # RelationArgument relation_argument_model['entities'] = [relation_entity_model] relation_argument_model['location'] = [22, 32] relation_argument_model['text'] = 'Best Actor' - relations_result_model = {} # RelationsResult + relations_result_model = {} # RelationsResult relations_result_model['score'] = 0.680715 relations_result_model['sentence'] = 'Leonardo DiCaprio won Best Actor in a Leading Role for his performance.' relations_result_model['type'] = 'awardedTo' relations_result_model['arguments'] = [relation_argument_model] - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' - semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject semantic_roles_result_subject_model['text'] = 'IBM' semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'have' semantic_roles_verb_model['tense'] = 'present' - semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model = {} # SemanticRolesResultAction semantic_roles_result_action_model['text'] = 'has' semantic_roles_result_action_model['normalized'] = 'have' semantic_roles_result_action_model['verb'] = semantic_roles_verb_model - semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model = {} # SemanticRolesResultObject semantic_roles_result_object_model['text'] = 'one of the largest workforces in the world' semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_result_model = {} # SemanticRolesResult + semantic_roles_result_model = {} # SemanticRolesResult semantic_roles_result_model['sentence'] = 'IBM has one of the largest workforces in the world' semantic_roles_result_model['subject'] = semantic_roles_result_subject_model semantic_roles_result_model['action'] = semantic_roles_result_action_model semantic_roles_result_model['object'] = semantic_roles_result_object_model - document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model = {} # DocumentSentimentResults document_sentiment_results_model['label'] = 'testString' document_sentiment_results_model['score'] = 72.5 - targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model = {} # TargetedSentimentResults targeted_sentiment_results_model['text'] = 'testString' targeted_sentiment_results_model['score'] = 72.5 - sentiment_result_model = {} # SentimentResult + sentiment_result_model = {} # SentimentResult sentiment_result_model['document'] = document_sentiment_results_model sentiment_result_model['targets'] = [targeted_sentiment_results_model] - token_result_model = {} # TokenResult + token_result_model = {} # TokenResult token_result_model['text'] = 'testString' token_result_model['part_of_speech'] = 'ADJ' token_result_model['location'] = [38] token_result_model['lemma'] = 'testString' - sentence_result_model = {} # SentenceResult + sentence_result_model = {} # SentenceResult sentence_result_model['text'] = 'testString' sentence_result_model['location'] = [38] - syntax_result_model = {} # SyntaxResult + syntax_result_model = {} # SyntaxResult syntax_result_model['tokens'] = [token_result_model] syntax_result_model['sentences'] = [sentence_result_model] @@ -1727,7 +1794,8 @@ def test_analysis_results_serialization(self): analysis_results_model_json2 = analysis_results_model.to_dict() assert analysis_results_model_json2 == analysis_results_model_json -class TestModel_AnalysisResultsUsage(): + +class TestModel_AnalysisResultsUsage: """ Test Class for AnalysisResultsUsage """ @@ -1758,7 +1826,8 @@ def test_analysis_results_usage_serialization(self): analysis_results_usage_model_json2 = analysis_results_usage_model.to_dict() assert analysis_results_usage_model_json2 == analysis_results_usage_model_json -class TestModel_Author(): + +class TestModel_Author: """ Test Class for Author """ @@ -1787,7 +1856,8 @@ def test_author_serialization(self): author_model_json2 = author_model.to_dict() assert author_model_json2 == author_model_json -class TestModel_CategoriesModel(): + +class TestModel_CategoriesModel: """ Test Class for CategoriesModel """ @@ -1799,12 +1869,12 @@ def test_categories_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a CategoriesModel model categories_model_model_json = {} categories_model_model_json['name'] = 'testString' - categories_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} + categories_model_model_json['user_metadata'] = {'region': 'North America', 'latest': True} categories_model_model_json['language'] = 'testString' categories_model_model_json['description'] = 'testString' categories_model_model_json['model_version'] = 'testString' @@ -1833,7 +1903,8 @@ def test_categories_model_serialization(self): categories_model_model_json2 = categories_model_model.to_dict() assert categories_model_model_json2 == categories_model_model_json -class TestModel_CategoriesModelList(): + +class TestModel_CategoriesModelList: """ Test Class for CategoriesModelList """ @@ -1845,11 +1916,11 @@ def test_categories_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - categories_model_model = {} # CategoriesModel + categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {'key1': 'unknown type: dict'} + categories_model_model['user_metadata'] = {'region': 'North America', 'latest': True} categories_model_model['language'] = 'testString' categories_model_model['description'] = 'testString' categories_model_model['model_version'] = 'testString' @@ -1882,7 +1953,8 @@ def test_categories_model_list_serialization(self): categories_model_list_model_json2 = categories_model_list_model.to_dict() assert categories_model_list_model_json2 == categories_model_list_model_json -class TestModel_CategoriesOptions(): + +class TestModel_CategoriesOptions: """ Test Class for CategoriesOptions """ @@ -1895,7 +1967,7 @@ def test_categories_options_serialization(self): # Construct a json representation of a CategoriesOptions model categories_options_model_json = {} categories_options_model_json['explanation'] = False - categories_options_model_json['limit'] = 10 + categories_options_model_json['limit'] = 3 categories_options_model_json['model'] = 'testString' # Construct a model instance of CategoriesOptions by calling from_dict on the json representation @@ -1913,7 +1985,8 @@ def test_categories_options_serialization(self): categories_options_model_json2 = categories_options_model.to_dict() assert categories_options_model_json2 == categories_options_model_json -class TestModel_CategoriesRelevantText(): + +class TestModel_CategoriesRelevantText: """ Test Class for CategoriesRelevantText """ @@ -1942,7 +2015,8 @@ def test_categories_relevant_text_serialization(self): categories_relevant_text_model_json2 = categories_relevant_text_model.to_dict() assert categories_relevant_text_model_json2 == categories_relevant_text_model_json -class TestModel_CategoriesResult(): + +class TestModel_CategoriesResult: """ Test Class for CategoriesResult """ @@ -1954,10 +2028,10 @@ def test_categories_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' - categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model = {} # CategoriesResultExplanation categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] # Construct a json representation of a CategoriesResult model @@ -1981,7 +2055,8 @@ def test_categories_result_serialization(self): categories_result_model_json2 = categories_result_model.to_dict() assert categories_result_model_json2 == categories_result_model_json -class TestModel_CategoriesResultExplanation(): + +class TestModel_CategoriesResultExplanation: """ Test Class for CategoriesResultExplanation """ @@ -1993,7 +2068,7 @@ def test_categories_result_explanation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' # Construct a json representation of a CategoriesResultExplanation model @@ -2015,7 +2090,8 @@ def test_categories_result_explanation_serialization(self): categories_result_explanation_model_json2 = categories_result_explanation_model.to_dict() assert categories_result_explanation_model_json2 == categories_result_explanation_model_json -class TestModel_ClassificationsModel(): + +class TestModel_ClassificationsModel: """ Test Class for ClassificationsModel """ @@ -2027,12 +2103,12 @@ def test_classifications_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} classifications_model_model_json['name'] = 'testString' - classifications_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} + classifications_model_model_json['user_metadata'] = {'region': 'North America', 'latest': True} classifications_model_model_json['language'] = 'testString' classifications_model_model_json['description'] = 'testString' classifications_model_model_json['model_version'] = 'testString' @@ -2061,7 +2137,8 @@ def test_classifications_model_serialization(self): classifications_model_model_json2 = classifications_model_model.to_dict() assert classifications_model_model_json2 == classifications_model_model_json -class TestModel_ClassificationsModelList(): + +class TestModel_ClassificationsModelList: """ Test Class for ClassificationsModelList """ @@ -2073,11 +2150,11 @@ def test_classifications_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - classifications_model_model = {} # ClassificationsModel + classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {'key1': 'unknown type: dict'} + classifications_model_model['user_metadata'] = {'region': 'North America', 'latest': True} classifications_model_model['language'] = 'testString' classifications_model_model['description'] = 'testString' classifications_model_model['model_version'] = 'testString' @@ -2110,7 +2187,8 @@ def test_classifications_model_list_serialization(self): classifications_model_list_model_json2 = classifications_model_list_model.to_dict() assert classifications_model_list_model_json2 == classifications_model_list_model_json -class TestModel_ClassificationsOptions(): + +class TestModel_ClassificationsOptions: """ Test Class for ClassificationsOptions """ @@ -2139,7 +2217,8 @@ def test_classifications_options_serialization(self): classifications_options_model_json2 = classifications_options_model.to_dict() assert classifications_options_model_json2 == classifications_options_model_json -class TestModel_ClassificationsResult(): + +class TestModel_ClassificationsResult: """ Test Class for ClassificationsResult """ @@ -2169,7 +2248,8 @@ def test_classifications_result_serialization(self): classifications_result_model_json2 = classifications_result_model.to_dict() assert classifications_result_model_json2 == classifications_result_model_json -class TestModel_ClassificationsTrainingParameters(): + +class TestModel_ClassificationsTrainingParameters: """ Test Class for ClassificationsTrainingParameters """ @@ -2198,7 +2278,8 @@ def test_classifications_training_parameters_serialization(self): classifications_training_parameters_model_json2 = classifications_training_parameters_model.to_dict() assert classifications_training_parameters_model_json2 == classifications_training_parameters_model_json -class TestModel_ConceptsOptions(): + +class TestModel_ConceptsOptions: """ Test Class for ConceptsOptions """ @@ -2210,7 +2291,7 @@ def test_concepts_options_serialization(self): # Construct a json representation of a ConceptsOptions model concepts_options_model_json = {} - concepts_options_model_json['limit'] = 50 + concepts_options_model_json['limit'] = 8 # Construct a model instance of ConceptsOptions by calling from_dict on the json representation concepts_options_model = ConceptsOptions.from_dict(concepts_options_model_json) @@ -2227,7 +2308,8 @@ def test_concepts_options_serialization(self): concepts_options_model_json2 = concepts_options_model.to_dict() assert concepts_options_model_json2 == concepts_options_model_json -class TestModel_ConceptsResult(): + +class TestModel_ConceptsResult: """ Test Class for ConceptsResult """ @@ -2258,7 +2340,8 @@ def test_concepts_result_serialization(self): concepts_result_model_json2 = concepts_result_model.to_dict() assert concepts_result_model_json2 == concepts_result_model_json -class TestModel_DeleteModelResults(): + +class TestModel_DeleteModelResults: """ Test Class for DeleteModelResults """ @@ -2287,7 +2370,8 @@ def test_delete_model_results_serialization(self): delete_model_results_model_json2 = delete_model_results_model.to_dict() assert delete_model_results_model_json2 == delete_model_results_model_json -class TestModel_DisambiguationResult(): + +class TestModel_DisambiguationResult: """ Test Class for DisambiguationResult """ @@ -2318,7 +2402,8 @@ def test_disambiguation_result_serialization(self): disambiguation_result_model_json2 = disambiguation_result_model.to_dict() assert disambiguation_result_model_json2 == disambiguation_result_model_json -class TestModel_DocumentEmotionResults(): + +class TestModel_DocumentEmotionResults: """ Test Class for DocumentEmotionResults """ @@ -2330,7 +2415,7 @@ def test_document_emotion_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 @@ -2356,7 +2441,8 @@ def test_document_emotion_results_serialization(self): document_emotion_results_model_json2 = document_emotion_results_model.to_dict() assert document_emotion_results_model_json2 == document_emotion_results_model_json -class TestModel_DocumentSentimentResults(): + +class TestModel_DocumentSentimentResults: """ Test Class for DocumentSentimentResults """ @@ -2386,7 +2472,8 @@ def test_document_sentiment_results_serialization(self): document_sentiment_results_model_json2 = document_sentiment_results_model.to_dict() assert document_sentiment_results_model_json2 == document_sentiment_results_model_json -class TestModel_EmotionOptions(): + +class TestModel_EmotionOptions: """ Test Class for EmotionOptions """ @@ -2416,7 +2503,8 @@ def test_emotion_options_serialization(self): emotion_options_model_json2 = emotion_options_model.to_dict() assert emotion_options_model_json2 == emotion_options_model_json -class TestModel_EmotionResult(): + +class TestModel_EmotionResult: """ Test Class for EmotionResult """ @@ -2428,17 +2516,17 @@ def test_emotion_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 0.041796 emotion_scores_model['disgust'] = 0.022637 emotion_scores_model['fear'] = 0.033387 emotion_scores_model['joy'] = 0.563273 emotion_scores_model['sadness'] = 0.32665 - document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model = {} # DocumentEmotionResults document_emotion_results_model['emotion'] = emotion_scores_model - targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model = {} # TargetedEmotionResults targeted_emotion_results_model['text'] = 'apples' targeted_emotion_results_model['emotion'] = emotion_scores_model @@ -2462,7 +2550,8 @@ def test_emotion_result_serialization(self): emotion_result_model_json2 = emotion_result_model.to_dict() assert emotion_result_model_json2 == emotion_result_model_json -class TestModel_EmotionScores(): + +class TestModel_EmotionScores: """ Test Class for EmotionScores """ @@ -2495,7 +2584,8 @@ def test_emotion_scores_serialization(self): emotion_scores_model_json2 = emotion_scores_model.to_dict() assert emotion_scores_model_json2 == emotion_scores_model_json -class TestModel_EntitiesOptions(): + +class TestModel_EntitiesOptions: """ Test Class for EntitiesOptions """ @@ -2507,7 +2597,7 @@ def test_entities_options_serialization(self): # Construct a json representation of a EntitiesOptions model entities_options_model_json = {} - entities_options_model_json['limit'] = 250 + entities_options_model_json['limit'] = 50 entities_options_model_json['mentions'] = False entities_options_model_json['model'] = 'testString' entities_options_model_json['sentiment'] = False @@ -2528,7 +2618,8 @@ def test_entities_options_serialization(self): entities_options_model_json2 = entities_options_model.to_dict() assert entities_options_model_json2 == entities_options_model_json -class TestModel_EntitiesResult(): + +class TestModel_EntitiesResult: """ Test Class for EntitiesResult """ @@ -2540,22 +2631,22 @@ def test_entities_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['location'] = [38] entity_mention_model['confidence'] = 72.5 - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 - disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model = {} # DisambiguationResult disambiguation_result_model['name'] = 'testString' disambiguation_result_model['dbpedia_resource'] = 'testString' disambiguation_result_model['subtype'] = ['testString'] @@ -2587,7 +2678,8 @@ def test_entities_result_serialization(self): entities_result_model_json2 = entities_result_model.to_dict() assert entities_result_model_json2 == entities_result_model_json -class TestModel_EntityMention(): + +class TestModel_EntityMention: """ Test Class for EntityMention """ @@ -2618,7 +2710,8 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestModel_FeatureSentimentResults(): + +class TestModel_FeatureSentimentResults: """ Test Class for FeatureSentimentResults """ @@ -2647,7 +2740,8 @@ def test_feature_sentiment_results_serialization(self): feature_sentiment_results_model_json2 = feature_sentiment_results_model.to_dict() assert feature_sentiment_results_model_json2 == feature_sentiment_results_model_json -class TestModel_Features(): + +class TestModel_Features: """ Test Class for Features """ @@ -2659,53 +2753,53 @@ def test_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - classifications_options_model = {} # ClassificationsOptions + classifications_options_model = {} # ClassificationsOptions classifications_options_model['model'] = 'testString' - concepts_options_model = {} # ConceptsOptions - concepts_options_model['limit'] = 50 + concepts_options_model = {} # ConceptsOptions + concepts_options_model['limit'] = 8 - emotion_options_model = {} # EmotionOptions + emotion_options_model = {} # EmotionOptions emotion_options_model['document'] = True emotion_options_model['targets'] = ['testString'] - entities_options_model = {} # EntitiesOptions - entities_options_model['limit'] = 250 + entities_options_model = {} # EntitiesOptions + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False entities_options_model['emotion'] = False - keywords_options_model = {} # KeywordsOptions - keywords_options_model['limit'] = 250 + keywords_options_model = {} # KeywordsOptions + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False - relations_options_model = {} # RelationsOptions + relations_options_model = {} # RelationsOptions relations_options_model['model'] = 'testString' - semantic_roles_options_model = {} # SemanticRolesOptions - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model = {} # SemanticRolesOptions + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False - sentiment_options_model = {} # SentimentOptions + sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - summarization_options_model = {} # SummarizationOptions - summarization_options_model['limit'] = 10 + summarization_options_model = {} # SummarizationOptions + summarization_options_model['limit'] = 3 - categories_options_model = {} # CategoriesOptions + categories_options_model = {} # CategoriesOptions categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' - syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True syntax_options_tokens_model['part_of_speech'] = True - syntax_options_model = {} # SyntaxOptions + syntax_options_model = {} # SyntaxOptions syntax_options_model['tokens'] = syntax_options_tokens_model syntax_options_model['sentences'] = True @@ -2716,7 +2810,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = {'foo': 'bar'} + features_model_json['metadata'] = {'anyKey': 'anyValue'} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -2739,7 +2833,8 @@ def test_features_serialization(self): features_model_json2 = features_model.to_dict() assert features_model_json2 == features_model_json -class TestModel_FeaturesResultsMetadata(): + +class TestModel_FeaturesResultsMetadata: """ Test Class for FeaturesResultsMetadata """ @@ -2751,10 +2846,10 @@ def test_features_results_metadata_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - author_model = {} # Author + author_model = {} # Author author_model['name'] = 'testString' - feed_model = {} # Feed + feed_model = {} # Feed feed_model['link'] = 'testString' # Construct a json representation of a FeaturesResultsMetadata model @@ -2780,7 +2875,8 @@ def test_features_results_metadata_serialization(self): features_results_metadata_model_json2 = features_results_metadata_model.to_dict() assert features_results_metadata_model_json2 == features_results_metadata_model_json -class TestModel_Feed(): + +class TestModel_Feed: """ Test Class for Feed """ @@ -2809,7 +2905,8 @@ def test_feed_serialization(self): feed_model_json2 = feed_model.to_dict() assert feed_model_json2 == feed_model_json -class TestModel_KeywordsOptions(): + +class TestModel_KeywordsOptions: """ Test Class for KeywordsOptions """ @@ -2821,7 +2918,7 @@ def test_keywords_options_serialization(self): # Construct a json representation of a KeywordsOptions model keywords_options_model_json = {} - keywords_options_model_json['limit'] = 250 + keywords_options_model_json['limit'] = 50 keywords_options_model_json['sentiment'] = False keywords_options_model_json['emotion'] = False @@ -2840,7 +2937,8 @@ def test_keywords_options_serialization(self): keywords_options_model_json2 = keywords_options_model.to_dict() assert keywords_options_model_json2 == keywords_options_model_json -class TestModel_KeywordsResult(): + +class TestModel_KeywordsResult: """ Test Class for KeywordsResult """ @@ -2852,14 +2950,14 @@ def test_keywords_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 # Construct a json representation of a KeywordsResult model @@ -2885,7 +2983,8 @@ def test_keywords_result_serialization(self): keywords_result_model_json2 = keywords_result_model.to_dict() assert keywords_result_model_json2 == keywords_result_model_json -class TestModel_ListModelsResults(): + +class TestModel_ListModelsResults: """ Test Class for ListModelsResults """ @@ -2897,7 +2996,7 @@ def test_list_models_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_model = {} # Model + model_model = {} # Model model_model['status'] = 'starting' model_model['model_id'] = 'testString' model_model['language'] = 'testString' @@ -2927,7 +3026,8 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json -class TestModel_Model(): + +class TestModel_Model: """ Test Class for Model """ @@ -2964,7 +3064,8 @@ def test_model_serialization(self): model_model_json2 = model_model.to_dict() assert model_model_json2 == model_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -2992,7 +3093,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_RelationArgument(): + +class TestModel_RelationArgument: """ Test Class for RelationArgument """ @@ -3004,7 +3106,7 @@ def test_relation_argument_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'testString' relation_entity_model['type'] = 'testString' @@ -3029,7 +3131,8 @@ def test_relation_argument_serialization(self): relation_argument_model_json2 = relation_argument_model.to_dict() assert relation_argument_model_json2 == relation_argument_model_json -class TestModel_RelationEntity(): + +class TestModel_RelationEntity: """ Test Class for RelationEntity """ @@ -3059,7 +3162,8 @@ def test_relation_entity_serialization(self): relation_entity_model_json2 = relation_entity_model.to_dict() assert relation_entity_model_json2 == relation_entity_model_json -class TestModel_RelationsOptions(): + +class TestModel_RelationsOptions: """ Test Class for RelationsOptions """ @@ -3088,7 +3192,8 @@ def test_relations_options_serialization(self): relations_options_model_json2 = relations_options_model.to_dict() assert relations_options_model_json2 == relations_options_model_json -class TestModel_RelationsResult(): + +class TestModel_RelationsResult: """ Test Class for RelationsResult """ @@ -3100,11 +3205,11 @@ def test_relations_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'testString' relation_entity_model['type'] = 'testString' - relation_argument_model = {} # RelationArgument + relation_argument_model = {} # RelationArgument relation_argument_model['entities'] = [relation_entity_model] relation_argument_model['location'] = [38] relation_argument_model['text'] = 'testString' @@ -3131,7 +3236,8 @@ def test_relations_result_serialization(self): relations_result_model_json2 = relations_result_model.to_dict() assert relations_result_model_json2 == relations_result_model_json -class TestModel_SemanticRolesEntity(): + +class TestModel_SemanticRolesEntity: """ Test Class for SemanticRolesEntity """ @@ -3161,7 +3267,8 @@ def test_semantic_roles_entity_serialization(self): semantic_roles_entity_model_json2 = semantic_roles_entity_model.to_dict() assert semantic_roles_entity_model_json2 == semantic_roles_entity_model_json -class TestModel_SemanticRolesKeyword(): + +class TestModel_SemanticRolesKeyword: """ Test Class for SemanticRolesKeyword """ @@ -3190,7 +3297,8 @@ def test_semantic_roles_keyword_serialization(self): semantic_roles_keyword_model_json2 = semantic_roles_keyword_model.to_dict() assert semantic_roles_keyword_model_json2 == semantic_roles_keyword_model_json -class TestModel_SemanticRolesOptions(): + +class TestModel_SemanticRolesOptions: """ Test Class for SemanticRolesOptions """ @@ -3202,7 +3310,7 @@ def test_semantic_roles_options_serialization(self): # Construct a json representation of a SemanticRolesOptions model semantic_roles_options_model_json = {} - semantic_roles_options_model_json['limit'] = 38 + semantic_roles_options_model_json['limit'] = 50 semantic_roles_options_model_json['keywords'] = False semantic_roles_options_model_json['entities'] = False @@ -3221,7 +3329,8 @@ def test_semantic_roles_options_serialization(self): semantic_roles_options_model_json2 = semantic_roles_options_model.to_dict() assert semantic_roles_options_model_json2 == semantic_roles_options_model_json -class TestModel_SemanticRolesResult(): + +class TestModel_SemanticRolesResult: """ Test Class for SemanticRolesResult """ @@ -3233,28 +3342,28 @@ def test_semantic_roles_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' - semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject semantic_roles_result_subject_model['text'] = 'testString' semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'testString' semantic_roles_verb_model['tense'] = 'testString' - semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model = {} # SemanticRolesResultAction semantic_roles_result_action_model['text'] = 'testString' semantic_roles_result_action_model['normalized'] = 'testString' semantic_roles_result_action_model['verb'] = semantic_roles_verb_model - semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model = {} # SemanticRolesResultObject semantic_roles_result_object_model['text'] = 'testString' semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] @@ -3280,7 +3389,8 @@ def test_semantic_roles_result_serialization(self): semantic_roles_result_model_json2 = semantic_roles_result_model.to_dict() assert semantic_roles_result_model_json2 == semantic_roles_result_model_json -class TestModel_SemanticRolesResultAction(): + +class TestModel_SemanticRolesResultAction: """ Test Class for SemanticRolesResultAction """ @@ -3292,7 +3402,7 @@ def test_semantic_roles_result_action_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'testString' semantic_roles_verb_model['tense'] = 'testString' @@ -3317,7 +3427,8 @@ def test_semantic_roles_result_action_serialization(self): semantic_roles_result_action_model_json2 = semantic_roles_result_action_model.to_dict() assert semantic_roles_result_action_model_json2 == semantic_roles_result_action_model_json -class TestModel_SemanticRolesResultObject(): + +class TestModel_SemanticRolesResultObject: """ Test Class for SemanticRolesResultObject """ @@ -3329,7 +3440,7 @@ def test_semantic_roles_result_object_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' # Construct a json representation of a SemanticRolesResultObject model @@ -3352,7 +3463,8 @@ def test_semantic_roles_result_object_serialization(self): semantic_roles_result_object_model_json2 = semantic_roles_result_object_model.to_dict() assert semantic_roles_result_object_model_json2 == semantic_roles_result_object_model_json -class TestModel_SemanticRolesResultSubject(): + +class TestModel_SemanticRolesResultSubject: """ Test Class for SemanticRolesResultSubject """ @@ -3364,11 +3476,11 @@ def test_semantic_roles_result_subject_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' # Construct a json representation of a SemanticRolesResultSubject model @@ -3392,7 +3504,8 @@ def test_semantic_roles_result_subject_serialization(self): semantic_roles_result_subject_model_json2 = semantic_roles_result_subject_model.to_dict() assert semantic_roles_result_subject_model_json2 == semantic_roles_result_subject_model_json -class TestModel_SemanticRolesVerb(): + +class TestModel_SemanticRolesVerb: """ Test Class for SemanticRolesVerb """ @@ -3422,7 +3535,8 @@ def test_semantic_roles_verb_serialization(self): semantic_roles_verb_model_json2 = semantic_roles_verb_model.to_dict() assert semantic_roles_verb_model_json2 == semantic_roles_verb_model_json -class TestModel_SentenceResult(): + +class TestModel_SentenceResult: """ Test Class for SentenceResult """ @@ -3452,7 +3566,8 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json -class TestModel_SentimentOptions(): + +class TestModel_SentimentOptions: """ Test Class for SentimentOptions """ @@ -3482,7 +3597,8 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json2 = sentiment_options_model.to_dict() assert sentiment_options_model_json2 == sentiment_options_model_json -class TestModel_SentimentResult(): + +class TestModel_SentimentResult: """ Test Class for SentimentResult """ @@ -3494,11 +3610,11 @@ def test_sentiment_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model = {} # DocumentSentimentResults document_sentiment_results_model['label'] = 'positive' document_sentiment_results_model['score'] = 0.127034 - targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model = {} # TargetedSentimentResults targeted_sentiment_results_model['text'] = 'stocks' targeted_sentiment_results_model['score'] = 0.279964 @@ -3522,7 +3638,8 @@ def test_sentiment_result_serialization(self): sentiment_result_model_json2 = sentiment_result_model.to_dict() assert sentiment_result_model_json2 == sentiment_result_model_json -class TestModel_SummarizationOptions(): + +class TestModel_SummarizationOptions: """ Test Class for SummarizationOptions """ @@ -3534,7 +3651,7 @@ def test_summarization_options_serialization(self): # Construct a json representation of a SummarizationOptions model summarization_options_model_json = {} - summarization_options_model_json['limit'] = 10 + summarization_options_model_json['limit'] = 3 # Construct a model instance of SummarizationOptions by calling from_dict on the json representation summarization_options_model = SummarizationOptions.from_dict(summarization_options_model_json) @@ -3551,7 +3668,8 @@ def test_summarization_options_serialization(self): summarization_options_model_json2 = summarization_options_model.to_dict() assert summarization_options_model_json2 == summarization_options_model_json -class TestModel_SyntaxOptions(): + +class TestModel_SyntaxOptions: """ Test Class for SyntaxOptions """ @@ -3563,7 +3681,7 @@ def test_syntax_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True syntax_options_tokens_model['part_of_speech'] = True @@ -3587,7 +3705,8 @@ def test_syntax_options_serialization(self): syntax_options_model_json2 = syntax_options_model.to_dict() assert syntax_options_model_json2 == syntax_options_model_json -class TestModel_SyntaxOptionsTokens(): + +class TestModel_SyntaxOptionsTokens: """ Test Class for SyntaxOptionsTokens """ @@ -3617,7 +3736,8 @@ def test_syntax_options_tokens_serialization(self): syntax_options_tokens_model_json2 = syntax_options_tokens_model.to_dict() assert syntax_options_tokens_model_json2 == syntax_options_tokens_model_json -class TestModel_SyntaxResult(): + +class TestModel_SyntaxResult: """ Test Class for SyntaxResult """ @@ -3629,13 +3749,13 @@ def test_syntax_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - token_result_model = {} # TokenResult + token_result_model = {} # TokenResult token_result_model['text'] = 'testString' token_result_model['part_of_speech'] = 'ADJ' token_result_model['location'] = [38] token_result_model['lemma'] = 'testString' - sentence_result_model = {} # SentenceResult + sentence_result_model = {} # SentenceResult sentence_result_model['text'] = 'testString' sentence_result_model['location'] = [38] @@ -3659,7 +3779,8 @@ def test_syntax_result_serialization(self): syntax_result_model_json2 = syntax_result_model.to_dict() assert syntax_result_model_json2 == syntax_result_model_json -class TestModel_TargetedEmotionResults(): + +class TestModel_TargetedEmotionResults: """ Test Class for TargetedEmotionResults """ @@ -3671,7 +3792,7 @@ def test_targeted_emotion_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 @@ -3698,7 +3819,8 @@ def test_targeted_emotion_results_serialization(self): targeted_emotion_results_model_json2 = targeted_emotion_results_model.to_dict() assert targeted_emotion_results_model_json2 == targeted_emotion_results_model_json -class TestModel_TargetedSentimentResults(): + +class TestModel_TargetedSentimentResults: """ Test Class for TargetedSentimentResults """ @@ -3728,7 +3850,8 @@ def test_targeted_sentiment_results_serialization(self): targeted_sentiment_results_model_json2 = targeted_sentiment_results_model.to_dict() assert targeted_sentiment_results_model_json2 == targeted_sentiment_results_model_json -class TestModel_TokenResult(): + +class TestModel_TokenResult: """ Test Class for TokenResult """ diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index b2578b8f..922c7815 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -69,7 +68,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -82,16 +82,17 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -105,7 +106,8 @@ def test_list_models_all_params_with_retries(self): _service.disable_retries() self.test_list_models_all_params() -class TestGetModel(): + +class TestGetModel: """ Test Class for get_model """ @@ -118,11 +120,13 @@ def test_get_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'ar-MS_BroadbandModel' @@ -130,7 +134,7 @@ def test_get_model_all_params(self): # Invoke method response = _service.get_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -154,11 +158,13 @@ def test_get_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'ar-MS_BroadbandModel' @@ -168,7 +174,7 @@ def test_get_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_model(**req_copy) @@ -181,6 +187,7 @@ def test_get_model_value_error_with_retries(self): _service.disable_retries() self.test_get_model_value_error() + # endregion ############################################################################## # End of Service: Models @@ -191,7 +198,8 @@ def test_get_model_value_error_with_retries(self): ############################################################################## # region -class TestRecognize(): + +class TestRecognize: """ Test Class for recognize """ @@ -204,11 +212,13 @@ def test_recognize_all_params(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -218,25 +228,26 @@ def test_recognize_all_params(self): acoustic_customization_id = 'testString' base_model_version = 'testString' customization_weight = 72.5 - inactivity_timeout = 38 + inactivity_timeout = 30 keywords = ['testString'] keywords_threshold = 36.0 - max_alternatives = 38 + max_alternatives = 1 word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True smart_formatting = False + smart_formatting_version = False speaker_labels = False grammar_name = 'testString' redaction = False audio_metrics = False - end_of_phrase_silence_time = 72.5 + end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 36.0 - background_audio_suppression = 36.0 + speech_detector_sensitivity = 0.5 + background_audio_suppression = 0.0 low_latency = False - character_insertion_bias = 36.0 + character_insertion_bias = 0.0 # Invoke method response = _service.recognize( @@ -256,6 +267,7 @@ def test_recognize_all_params(self): timestamps=timestamps, profanity_filter=profanity_filter, smart_formatting=smart_formatting, + smart_formatting_version=smart_formatting_version, speaker_labels=speaker_labels, grammar_name=grammar_name, redaction=redaction, @@ -266,14 +278,14 @@ def test_recognize_all_params(self): background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string assert 'language_customization_id={}'.format(language_customization_id) in query_string @@ -287,6 +299,7 @@ def test_recognize_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string @@ -313,11 +326,13 @@ def test_recognize_required_params(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -325,7 +340,7 @@ def test_recognize_required_params(self): # Invoke method response = _service.recognize( audio, - headers={} + headers={}, ) # Check for correct operation @@ -350,11 +365,13 @@ def test_recognize_value_error(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -364,7 +381,7 @@ def test_recognize_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.recognize(**req_copy) @@ -377,6 +394,7 @@ def test_recognize_value_error_with_retries(self): _service.disable_retries() self.test_recognize_value_error() + # endregion ############################################################################## # End of Service: Synchronous @@ -387,7 +405,8 @@ def test_recognize_value_error_with_retries(self): ############################################################################## # region -class TestRegisterCallback(): + +class TestRegisterCallback: """ Test Class for register_callback """ @@ -400,11 +419,13 @@ def test_register_callback_all_params(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -414,14 +435,14 @@ def test_register_callback_all_params(self): response = _service.register_callback( callback_url, user_secret=user_secret, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string assert 'user_secret={}'.format(user_secret) in query_string @@ -443,11 +464,13 @@ def test_register_callback_required_params(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -455,14 +478,14 @@ def test_register_callback_required_params(self): # Invoke method response = _service.register_callback( callback_url, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string @@ -483,11 +506,13 @@ def test_register_callback_value_error(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -497,7 +522,7 @@ def test_register_callback_value_error(self): "callback_url": callback_url, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.register_callback(**req_copy) @@ -510,7 +535,8 @@ def test_register_callback_value_error_with_retries(self): _service.disable_retries() self.test_register_callback_value_error() -class TestUnregisterCallback(): + +class TestUnregisterCallback: """ Test Class for unregister_callback """ @@ -522,9 +548,11 @@ def test_unregister_callback_all_params(self): """ # Set up mock url = preprocess_url('/v1/unregister_callback') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -532,14 +560,14 @@ def test_unregister_callback_all_params(self): # Invoke method response = _service.unregister_callback( callback_url, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string @@ -559,9 +587,11 @@ def test_unregister_callback_value_error(self): """ # Set up mock url = preprocess_url('/v1/unregister_callback') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -571,7 +601,7 @@ def test_unregister_callback_value_error(self): "callback_url": callback_url, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.unregister_callback(**req_copy) @@ -584,7 +614,8 @@ def test_unregister_callback_value_error_with_retries(self): _service.disable_retries() self.test_unregister_callback_value_error() -class TestCreateJob(): + +class TestCreateJob: """ Test Class for create_job """ @@ -597,11 +628,13 @@ def test_create_job_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -615,27 +648,28 @@ def test_create_job_all_params(self): acoustic_customization_id = 'testString' base_model_version = 'testString' customization_weight = 72.5 - inactivity_timeout = 38 + inactivity_timeout = 30 keywords = ['testString'] keywords_threshold = 36.0 - max_alternatives = 38 + max_alternatives = 1 word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True smart_formatting = False + smart_formatting_version = False speaker_labels = False grammar_name = 'testString' redaction = False processing_metrics = False - processing_metrics_interval = 36.0 + processing_metrics_interval = 1.0 audio_metrics = False - end_of_phrase_silence_time = 72.5 + end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 36.0 - background_audio_suppression = 36.0 + speech_detector_sensitivity = 0.5 + background_audio_suppression = 0.0 low_latency = False - character_insertion_bias = 36.0 + character_insertion_bias = 0.0 # Invoke method response = _service.create_job( @@ -659,6 +693,7 @@ def test_create_job_all_params(self): timestamps=timestamps, profanity_filter=profanity_filter, smart_formatting=smart_formatting, + smart_formatting_version=smart_formatting_version, speaker_labels=speaker_labels, grammar_name=grammar_name, redaction=redaction, @@ -671,14 +706,14 @@ def test_create_job_all_params(self): background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string assert 'callback_url={}'.format(callback_url) in query_string @@ -696,6 +731,7 @@ def test_create_job_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string @@ -723,11 +759,13 @@ def test_create_job_required_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -735,7 +773,7 @@ def test_create_job_required_params(self): # Invoke method response = _service.create_job( audio, - headers={} + headers={}, ) # Check for correct operation @@ -760,11 +798,13 @@ def test_create_job_value_error(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -774,7 +814,7 @@ def test_create_job_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_job(**req_copy) @@ -787,7 +827,8 @@ def test_create_job_value_error_with_retries(self): _service.disable_retries() self.test_create_job_value_error() -class TestCheckJobs(): + +class TestCheckJobs: """ Test Class for check_jobs """ @@ -800,16 +841,17 @@ def test_check_jobs_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.check_jobs() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -823,7 +865,8 @@ def test_check_jobs_all_params_with_retries(self): _service.disable_retries() self.test_check_jobs_all_params() -class TestCheckJob(): + +class TestCheckJob: """ Test Class for check_job """ @@ -836,11 +879,13 @@ def test_check_job_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values id = 'testString' @@ -848,7 +893,7 @@ def test_check_job_all_params(self): # Invoke method response = _service.check_job( id, - headers={} + headers={}, ) # Check for correct operation @@ -872,11 +917,13 @@ def test_check_job_value_error(self): # Set up mock url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values id = 'testString' @@ -886,7 +933,7 @@ def test_check_job_value_error(self): "id": id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.check_job(**req_copy) @@ -899,7 +946,8 @@ def test_check_job_value_error_with_retries(self): _service.disable_retries() self.test_check_job_value_error() -class TestDeleteJob(): + +class TestDeleteJob: """ Test Class for delete_job """ @@ -911,9 +959,11 @@ def test_delete_job_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values id = 'testString' @@ -921,7 +971,7 @@ def test_delete_job_all_params(self): # Invoke method response = _service.delete_job( id, - headers={} + headers={}, ) # Check for correct operation @@ -944,9 +994,11 @@ def test_delete_job_value_error(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values id = 'testString' @@ -956,7 +1008,7 @@ def test_delete_job_value_error(self): "id": id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_job(**req_copy) @@ -969,6 +1021,7 @@ def test_delete_job_value_error_with_retries(self): _service.disable_retries() self.test_delete_job_value_error() + # endregion ############################################################################## # End of Service: Asynchronous @@ -979,7 +1032,8 @@ def test_delete_job_value_error_with_retries(self): ############################################################################## # region -class TestCreateLanguageModel(): + +class TestCreateLanguageModel: """ Test Class for create_language_model """ @@ -992,11 +1046,13 @@ def test_create_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -1010,7 +1066,7 @@ def test_create_language_model_all_params(self): base_model_name, dialect=dialect, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -1040,11 +1096,13 @@ def test_create_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -1058,7 +1116,7 @@ def test_create_language_model_value_error(self): "base_model_name": base_model_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_language_model(**req_copy) @@ -1071,7 +1129,8 @@ def test_create_language_model_value_error_with_retries(self): _service.disable_retries() self.test_create_language_model_value_error() -class TestListLanguageModels(): + +class TestListLanguageModels: """ Test Class for list_language_models """ @@ -1084,11 +1143,13 @@ def test_list_language_models_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'ar-MS' @@ -1096,14 +1157,14 @@ def test_list_language_models_all_params(self): # Invoke method response = _service.list_language_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -1124,16 +1185,17 @@ def test_list_language_models_required_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_language_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1147,7 +1209,8 @@ def test_list_language_models_required_params_with_retries(self): _service.disable_retries() self.test_list_language_models_required_params() -class TestGetLanguageModel(): + +class TestGetLanguageModel: """ Test Class for get_language_model """ @@ -1160,11 +1223,13 @@ def test_get_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1172,7 +1237,7 @@ def test_get_language_model_all_params(self): # Invoke method response = _service.get_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1196,11 +1261,13 @@ def test_get_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1210,7 +1277,7 @@ def test_get_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_language_model(**req_copy) @@ -1223,7 +1290,8 @@ def test_get_language_model_value_error_with_retries(self): _service.disable_retries() self.test_get_language_model_value_error() -class TestDeleteLanguageModel(): + +class TestDeleteLanguageModel: """ Test Class for delete_language_model """ @@ -1235,9 +1303,11 @@ def test_delete_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1245,7 +1315,7 @@ def test_delete_language_model_all_params(self): # Invoke method response = _service.delete_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1268,9 +1338,11 @@ def test_delete_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1280,7 +1352,7 @@ def test_delete_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_language_model(**req_copy) @@ -1293,7 +1365,8 @@ def test_delete_language_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_language_model_value_error() -class TestTrainLanguageModel(): + +class TestTrainLanguageModel: """ Test Class for train_language_model """ @@ -1306,17 +1379,20 @@ def test_train_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' word_type_to_add = 'all' customization_weight = 72.5 strict = True + force = False # Invoke method response = _service.train_language_model( @@ -1324,18 +1400,20 @@ def test_train_language_model_all_params(self): word_type_to_add=word_type_to_add, customization_weight=customization_weight, strict=strict, - headers={} + force=force, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string assert 'strict={}'.format('true' if strict else 'false') in query_string + assert 'force={}'.format('true' if force else 'false') in query_string def test_train_language_model_all_params_with_retries(self): # Enable retries and run test_train_language_model_all_params. @@ -1354,11 +1432,13 @@ def test_train_language_model_required_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1366,7 +1446,7 @@ def test_train_language_model_required_params(self): # Invoke method response = _service.train_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1390,11 +1470,13 @@ def test_train_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1404,7 +1486,7 @@ def test_train_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.train_language_model(**req_copy) @@ -1417,7 +1499,8 @@ def test_train_language_model_value_error_with_retries(self): _service.disable_retries() self.test_train_language_model_value_error() -class TestResetLanguageModel(): + +class TestResetLanguageModel: """ Test Class for reset_language_model """ @@ -1429,9 +1512,11 @@ def test_reset_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1439,7 +1524,7 @@ def test_reset_language_model_all_params(self): # Invoke method response = _service.reset_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1462,9 +1547,11 @@ def test_reset_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1474,7 +1561,7 @@ def test_reset_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.reset_language_model(**req_copy) @@ -1487,7 +1574,8 @@ def test_reset_language_model_value_error_with_retries(self): _service.disable_retries() self.test_reset_language_model_value_error() -class TestUpgradeLanguageModel(): + +class TestUpgradeLanguageModel: """ Test Class for upgrade_language_model """ @@ -1499,9 +1587,11 @@ def test_upgrade_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1509,7 +1599,7 @@ def test_upgrade_language_model_all_params(self): # Invoke method response = _service.upgrade_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1532,9 +1622,11 @@ def test_upgrade_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1544,7 +1636,7 @@ def test_upgrade_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.upgrade_language_model(**req_copy) @@ -1557,6 +1649,7 @@ def test_upgrade_language_model_value_error_with_retries(self): _service.disable_retries() self.test_upgrade_language_model_value_error() + # endregion ############################################################################## # End of Service: CustomLanguageModels @@ -1567,7 +1660,8 @@ def test_upgrade_language_model_value_error_with_retries(self): ############################################################################## # region -class TestListCorpora(): + +class TestListCorpora: """ Test Class for list_corpora """ @@ -1580,11 +1674,13 @@ def test_list_corpora_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1592,7 +1688,7 @@ def test_list_corpora_all_params(self): # Invoke method response = _service.list_corpora( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1616,11 +1712,13 @@ def test_list_corpora_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1630,7 +1728,7 @@ def test_list_corpora_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_corpora(**req_copy) @@ -1643,7 +1741,8 @@ def test_list_corpora_value_error_with_retries(self): _service.disable_retries() self.test_list_corpora_value_error() -class TestAddCorpus(): + +class TestAddCorpus: """ Test Class for add_corpus """ @@ -1655,9 +1754,11 @@ def test_add_corpus_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1671,14 +1772,14 @@ def test_add_corpus_all_params(self): corpus_name, corpus_file, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string @@ -1698,9 +1799,11 @@ def test_add_corpus_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1712,7 +1815,7 @@ def test_add_corpus_required_params(self): customization_id, corpus_name, corpus_file, - headers={} + headers={}, ) # Check for correct operation @@ -1735,9 +1838,11 @@ def test_add_corpus_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1751,7 +1856,7 @@ def test_add_corpus_value_error(self): "corpus_file": corpus_file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_corpus(**req_copy) @@ -1764,7 +1869,8 @@ def test_add_corpus_value_error_with_retries(self): _service.disable_retries() self.test_add_corpus_value_error() -class TestGetCorpus(): + +class TestGetCorpus: """ Test Class for get_corpus """ @@ -1777,11 +1883,13 @@ def test_get_corpus_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1791,7 +1899,7 @@ def test_get_corpus_all_params(self): response = _service.get_corpus( customization_id, corpus_name, - headers={} + headers={}, ) # Check for correct operation @@ -1815,11 +1923,13 @@ def test_get_corpus_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1831,7 +1941,7 @@ def test_get_corpus_value_error(self): "corpus_name": corpus_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_corpus(**req_copy) @@ -1844,7 +1954,8 @@ def test_get_corpus_value_error_with_retries(self): _service.disable_retries() self.test_get_corpus_value_error() -class TestDeleteCorpus(): + +class TestDeleteCorpus: """ Test Class for delete_corpus """ @@ -1856,9 +1967,11 @@ def test_delete_corpus_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1868,7 +1981,7 @@ def test_delete_corpus_all_params(self): response = _service.delete_corpus( customization_id, corpus_name, - headers={} + headers={}, ) # Check for correct operation @@ -1891,9 +2004,11 @@ def test_delete_corpus_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1905,7 +2020,7 @@ def test_delete_corpus_value_error(self): "corpus_name": corpus_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_corpus(**req_copy) @@ -1918,6 +2033,7 @@ def test_delete_corpus_value_error_with_retries(self): _service.disable_retries() self.test_delete_corpus_value_error() + # endregion ############################################################################## # End of Service: CustomCorpora @@ -1928,7 +2044,8 @@ def test_delete_corpus_value_error_with_retries(self): ############################################################################## # region -class TestListWords(): + +class TestListWords: """ Test Class for list_words """ @@ -1940,12 +2057,14 @@ def test_list_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1957,14 +2076,14 @@ def test_list_words_all_params(self): customization_id, word_type=word_type, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'word_type={}'.format(word_type) in query_string assert 'sort={}'.format(sort) in query_string @@ -1985,12 +2104,14 @@ def test_list_words_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1998,7 +2119,7 @@ def test_list_words_required_params(self): # Invoke method response = _service.list_words( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2021,12 +2142,14 @@ def test_list_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2036,7 +2159,7 @@ def test_list_words_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_words(**req_copy) @@ -2049,7 +2172,8 @@ def test_list_words_value_error_with_retries(self): _service.disable_retries() self.test_list_words_value_error() -class TestAddWords(): + +class TestAddWords: """ Test Class for add_words """ @@ -2061,13 +2185,16 @@ def test_add_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Construct a dict representation of a CustomWord model custom_word_model = {} custom_word_model['word'] = 'testString' + custom_word_model['mapping_only'] = ['testString'] custom_word_model['sounds_like'] = ['testString'] custom_word_model['display_as'] = 'testString' @@ -2079,7 +2206,7 @@ def test_add_words_all_params(self): response = _service.add_words( customization_id, words, - headers={} + headers={}, ) # Check for correct operation @@ -2105,13 +2232,16 @@ def test_add_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Construct a dict representation of a CustomWord model custom_word_model = {} custom_word_model['word'] = 'testString' + custom_word_model['mapping_only'] = ['testString'] custom_word_model['sounds_like'] = ['testString'] custom_word_model['display_as'] = 'testString' @@ -2125,7 +2255,7 @@ def test_add_words_value_error(self): "words": words, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_words(**req_copy) @@ -2138,7 +2268,8 @@ def test_add_words_value_error_with_retries(self): _service.disable_retries() self.test_add_words_value_error() -class TestAddWord(): + +class TestAddWord: """ Test Class for add_word """ @@ -2150,14 +2281,17 @@ def test_add_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=201) + responses.add( + responses.PUT, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' word_name = 'testString' word = 'testString' + mapping_only = ['testString'] sounds_like = ['testString'] display_as = 'testString' @@ -2166,9 +2300,10 @@ def test_add_word_all_params(self): customization_id, word_name, word=word, + mapping_only=mapping_only, sounds_like=sounds_like, display_as=display_as, - headers={} + headers={}, ) # Check for correct operation @@ -2177,6 +2312,7 @@ def test_add_word_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['word'] == 'testString' + assert req_body['mapping_only'] == ['testString'] assert req_body['sounds_like'] == ['testString'] assert req_body['display_as'] == 'testString' @@ -2196,14 +2332,17 @@ def test_add_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=201) + responses.add( + responses.PUT, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' word_name = 'testString' word = 'testString' + mapping_only = ['testString'] sounds_like = ['testString'] display_as = 'testString' @@ -2213,7 +2352,7 @@ def test_add_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_word(**req_copy) @@ -2226,7 +2365,8 @@ def test_add_word_value_error_with_retries(self): _service.disable_retries() self.test_add_word_value_error() -class TestGetWord(): + +class TestGetWord: """ Test Class for get_word """ @@ -2238,12 +2378,14 @@ def test_get_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2253,7 +2395,7 @@ def test_get_word_all_params(self): response = _service.get_word( customization_id, word_name, - headers={} + headers={}, ) # Check for correct operation @@ -2276,12 +2418,14 @@ def test_get_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2293,7 +2437,7 @@ def test_get_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_word(**req_copy) @@ -2306,7 +2450,8 @@ def test_get_word_value_error_with_retries(self): _service.disable_retries() self.test_get_word_value_error() -class TestDeleteWord(): + +class TestDeleteWord: """ Test Class for delete_word """ @@ -2318,9 +2463,11 @@ def test_delete_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2330,7 +2477,7 @@ def test_delete_word_all_params(self): response = _service.delete_word( customization_id, word_name, - headers={} + headers={}, ) # Check for correct operation @@ -2353,9 +2500,11 @@ def test_delete_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2367,7 +2516,7 @@ def test_delete_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_word(**req_copy) @@ -2380,6 +2529,7 @@ def test_delete_word_value_error_with_retries(self): _service.disable_retries() self.test_delete_word_value_error() + # endregion ############################################################################## # End of Service: CustomWords @@ -2390,7 +2540,8 @@ def test_delete_word_value_error_with_retries(self): ############################################################################## # region -class TestListGrammars(): + +class TestListGrammars: """ Test Class for list_grammars """ @@ -2403,11 +2554,13 @@ def test_list_grammars_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2415,7 +2568,7 @@ def test_list_grammars_all_params(self): # Invoke method response = _service.list_grammars( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2439,11 +2592,13 @@ def test_list_grammars_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2453,7 +2608,7 @@ def test_list_grammars_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_grammars(**req_copy) @@ -2466,7 +2621,8 @@ def test_list_grammars_value_error_with_retries(self): _service.disable_retries() self.test_list_grammars_value_error() -class TestAddGrammar(): + +class TestAddGrammar: """ Test Class for add_grammar """ @@ -2478,9 +2634,11 @@ def test_add_grammar_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2496,14 +2654,14 @@ def test_add_grammar_all_params(self): grammar_file, content_type, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params @@ -2524,9 +2682,11 @@ def test_add_grammar_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2540,7 +2700,7 @@ def test_add_grammar_required_params(self): grammar_name, grammar_file, content_type, - headers={} + headers={}, ) # Check for correct operation @@ -2564,9 +2724,11 @@ def test_add_grammar_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2582,7 +2744,7 @@ def test_add_grammar_value_error(self): "content_type": content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_grammar(**req_copy) @@ -2595,7 +2757,8 @@ def test_add_grammar_value_error_with_retries(self): _service.disable_retries() self.test_add_grammar_value_error() -class TestGetGrammar(): + +class TestGetGrammar: """ Test Class for get_grammar """ @@ -2608,11 +2771,13 @@ def test_get_grammar_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2622,7 +2787,7 @@ def test_get_grammar_all_params(self): response = _service.get_grammar( customization_id, grammar_name, - headers={} + headers={}, ) # Check for correct operation @@ -2646,11 +2811,13 @@ def test_get_grammar_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2662,7 +2829,7 @@ def test_get_grammar_value_error(self): "grammar_name": grammar_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_grammar(**req_copy) @@ -2675,7 +2842,8 @@ def test_get_grammar_value_error_with_retries(self): _service.disable_retries() self.test_get_grammar_value_error() -class TestDeleteGrammar(): + +class TestDeleteGrammar: """ Test Class for delete_grammar """ @@ -2687,9 +2855,11 @@ def test_delete_grammar_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2699,7 +2869,7 @@ def test_delete_grammar_all_params(self): response = _service.delete_grammar( customization_id, grammar_name, - headers={} + headers={}, ) # Check for correct operation @@ -2722,9 +2892,11 @@ def test_delete_grammar_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2736,7 +2908,7 @@ def test_delete_grammar_value_error(self): "grammar_name": grammar_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_grammar(**req_copy) @@ -2749,6 +2921,7 @@ def test_delete_grammar_value_error_with_retries(self): _service.disable_retries() self.test_delete_grammar_value_error() + # endregion ############################################################################## # End of Service: CustomGrammars @@ -2759,7 +2932,8 @@ def test_delete_grammar_value_error_with_retries(self): ############################################################################## # region -class TestCreateAcousticModel(): + +class TestCreateAcousticModel: """ Test Class for create_acoustic_model """ @@ -2772,11 +2946,13 @@ def test_create_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -2788,7 +2964,7 @@ def test_create_acoustic_model_all_params(self): name, base_model_name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -2817,11 +2993,13 @@ def test_create_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -2834,7 +3012,7 @@ def test_create_acoustic_model_value_error(self): "base_model_name": base_model_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_acoustic_model(**req_copy) @@ -2847,7 +3025,8 @@ def test_create_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_create_acoustic_model_value_error() -class TestListAcousticModels(): + +class TestListAcousticModels: """ Test Class for list_acoustic_models """ @@ -2860,11 +3039,13 @@ def test_list_acoustic_models_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'ar-MS' @@ -2872,14 +3053,14 @@ def test_list_acoustic_models_all_params(self): # Invoke method response = _service.list_acoustic_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -2900,16 +3081,17 @@ def test_list_acoustic_models_required_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_acoustic_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -2923,7 +3105,8 @@ def test_list_acoustic_models_required_params_with_retries(self): _service.disable_retries() self.test_list_acoustic_models_required_params() -class TestGetAcousticModel(): + +class TestGetAcousticModel: """ Test Class for get_acoustic_model """ @@ -2936,11 +3119,13 @@ def test_get_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2948,7 +3133,7 @@ def test_get_acoustic_model_all_params(self): # Invoke method response = _service.get_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2972,11 +3157,13 @@ def test_get_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2986,7 +3173,7 @@ def test_get_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_acoustic_model(**req_copy) @@ -2999,7 +3186,8 @@ def test_get_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_get_acoustic_model_value_error() -class TestDeleteAcousticModel(): + +class TestDeleteAcousticModel: """ Test Class for delete_acoustic_model """ @@ -3011,9 +3199,11 @@ def test_delete_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3021,7 +3211,7 @@ def test_delete_acoustic_model_all_params(self): # Invoke method response = _service.delete_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3044,9 +3234,11 @@ def test_delete_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3056,7 +3248,7 @@ def test_delete_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_acoustic_model(**req_copy) @@ -3069,7 +3261,8 @@ def test_delete_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_acoustic_model_value_error() -class TestTrainAcousticModel(): + +class TestTrainAcousticModel: """ Test Class for train_acoustic_model """ @@ -3082,11 +3275,13 @@ def test_train_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3098,14 +3293,14 @@ def test_train_acoustic_model_all_params(self): customization_id, custom_language_model_id=custom_language_model_id, strict=strict, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string assert 'strict={}'.format('true' if strict else 'false') in query_string @@ -3127,11 +3322,13 @@ def test_train_acoustic_model_required_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3139,7 +3336,7 @@ def test_train_acoustic_model_required_params(self): # Invoke method response = _service.train_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3163,11 +3360,13 @@ def test_train_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3177,7 +3376,7 @@ def test_train_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.train_acoustic_model(**req_copy) @@ -3190,7 +3389,8 @@ def test_train_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_train_acoustic_model_value_error() -class TestResetAcousticModel(): + +class TestResetAcousticModel: """ Test Class for reset_acoustic_model """ @@ -3202,9 +3402,11 @@ def test_reset_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3212,7 +3414,7 @@ def test_reset_acoustic_model_all_params(self): # Invoke method response = _service.reset_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3235,9 +3437,11 @@ def test_reset_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3247,7 +3451,7 @@ def test_reset_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.reset_acoustic_model(**req_copy) @@ -3260,7 +3464,8 @@ def test_reset_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_reset_acoustic_model_value_error() -class TestUpgradeAcousticModel(): + +class TestUpgradeAcousticModel: """ Test Class for upgrade_acoustic_model """ @@ -3272,9 +3477,11 @@ def test_upgrade_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3286,14 +3493,14 @@ def test_upgrade_acoustic_model_all_params(self): customization_id, custom_language_model_id=custom_language_model_id, force=force, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string assert 'force={}'.format('true' if force else 'false') in query_string @@ -3314,9 +3521,11 @@ def test_upgrade_acoustic_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3324,7 +3533,7 @@ def test_upgrade_acoustic_model_required_params(self): # Invoke method response = _service.upgrade_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3347,9 +3556,11 @@ def test_upgrade_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3359,7 +3570,7 @@ def test_upgrade_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.upgrade_acoustic_model(**req_copy) @@ -3372,6 +3583,7 @@ def test_upgrade_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_upgrade_acoustic_model_value_error() + # endregion ############################################################################## # End of Service: CustomAcousticModels @@ -3382,7 +3594,8 @@ def test_upgrade_acoustic_model_value_error_with_retries(self): ############################################################################## # region -class TestListAudio(): + +class TestListAudio: """ Test Class for list_audio """ @@ -3395,11 +3608,13 @@ def test_list_audio_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3407,7 +3622,7 @@ def test_list_audio_all_params(self): # Invoke method response = _service.list_audio( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3431,11 +3646,13 @@ def test_list_audio_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3445,7 +3662,7 @@ def test_list_audio_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_audio(**req_copy) @@ -3458,7 +3675,8 @@ def test_list_audio_value_error_with_retries(self): _service.disable_retries() self.test_list_audio_value_error() -class TestAddAudio(): + +class TestAddAudio: """ Test Class for add_audio """ @@ -3470,9 +3688,11 @@ def test_add_audio_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3490,14 +3710,14 @@ def test_add_audio_all_params(self): content_type=content_type, contained_content_type=contained_content_type, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params @@ -3518,9 +3738,11 @@ def test_add_audio_required_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3532,7 +3754,7 @@ def test_add_audio_required_params(self): customization_id, audio_name, audio_resource, - headers={} + headers={}, ) # Check for correct operation @@ -3556,9 +3778,11 @@ def test_add_audio_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3572,7 +3796,7 @@ def test_add_audio_value_error(self): "audio_resource": audio_resource, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_audio(**req_copy) @@ -3585,7 +3809,8 @@ def test_add_audio_value_error_with_retries(self): _service.disable_retries() self.test_add_audio_value_error() -class TestGetAudio(): + +class TestGetAudio: """ Test Class for get_audio """ @@ -3598,11 +3823,13 @@ def test_get_audio_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3612,7 +3839,7 @@ def test_get_audio_all_params(self): response = _service.get_audio( customization_id, audio_name, - headers={} + headers={}, ) # Check for correct operation @@ -3636,11 +3863,13 @@ def test_get_audio_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3652,7 +3881,7 @@ def test_get_audio_value_error(self): "audio_name": audio_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_audio(**req_copy) @@ -3665,7 +3894,8 @@ def test_get_audio_value_error_with_retries(self): _service.disable_retries() self.test_get_audio_value_error() -class TestDeleteAudio(): + +class TestDeleteAudio: """ Test Class for delete_audio """ @@ -3677,9 +3907,11 @@ def test_delete_audio_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3689,7 +3921,7 @@ def test_delete_audio_all_params(self): response = _service.delete_audio( customization_id, audio_name, - headers={} + headers={}, ) # Check for correct operation @@ -3712,9 +3944,11 @@ def test_delete_audio_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3726,7 +3960,7 @@ def test_delete_audio_value_error(self): "audio_name": audio_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_audio(**req_copy) @@ -3739,6 +3973,7 @@ def test_delete_audio_value_error_with_retries(self): _service.disable_retries() self.test_delete_audio_value_error() + # endregion ############################################################################## # End of Service: CustomAudioResources @@ -3749,7 +3984,8 @@ def test_delete_audio_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -3761,9 +3997,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -3771,14 +4009,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -3798,9 +4036,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -3810,7 +4050,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -3823,6 +4063,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -3833,7 +4074,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AcousticModel(): + + +class TestModel_AcousticModel: """ Test Class for AcousticModel """ @@ -3873,7 +4116,8 @@ def test_acoustic_model_serialization(self): acoustic_model_model_json2 = acoustic_model_model.to_dict() assert acoustic_model_model_json2 == acoustic_model_model_json -class TestModel_AcousticModels(): + +class TestModel_AcousticModels: """ Test Class for AcousticModels """ @@ -3885,7 +4129,7 @@ def test_acoustic_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - acoustic_model_model = {} # AcousticModel + acoustic_model_model = {} # AcousticModel acoustic_model_model['customization_id'] = 'testString' acoustic_model_model['created'] = 'testString' acoustic_model_model['updated'] = 'testString' @@ -3918,7 +4162,8 @@ def test_acoustic_models_serialization(self): acoustic_models_model_json2 = acoustic_models_model.to_dict() assert acoustic_models_model_json2 == acoustic_models_model_json -class TestModel_AudioDetails(): + +class TestModel_AudioDetails: """ Test Class for AudioDetails """ @@ -3950,7 +4195,8 @@ def test_audio_details_serialization(self): audio_details_model_json2 = audio_details_model.to_dict() assert audio_details_model_json2 == audio_details_model_json -class TestModel_AudioListing(): + +class TestModel_AudioListing: """ Test Class for AudioListing """ @@ -3962,13 +4208,13 @@ def test_audio_listing_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 audio_details_model['compression'] = 'zip' - audio_resource_model = {} # AudioResource + audio_resource_model = {} # AudioResource audio_resource_model['duration'] = 38 audio_resource_model['name'] = 'testString' audio_resource_model['details'] = audio_details_model @@ -3998,7 +4244,8 @@ def test_audio_listing_serialization(self): audio_listing_model_json2 = audio_listing_model.to_dict() assert audio_listing_model_json2 == audio_listing_model_json -class TestModel_AudioMetrics(): + +class TestModel_AudioMetrics: """ Test Class for AudioMetrics """ @@ -4010,12 +4257,12 @@ def test_audio_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4046,7 +4293,8 @@ def test_audio_metrics_serialization(self): audio_metrics_model_json2 = audio_metrics_model.to_dict() assert audio_metrics_model_json2 == audio_metrics_model_json -class TestModel_AudioMetricsDetails(): + +class TestModel_AudioMetricsDetails: """ Test Class for AudioMetricsDetails """ @@ -4058,7 +4306,7 @@ def test_audio_metrics_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 @@ -4090,7 +4338,8 @@ def test_audio_metrics_details_serialization(self): audio_metrics_details_model_json2 = audio_metrics_details_model.to_dict() assert audio_metrics_details_model_json2 == audio_metrics_details_model_json -class TestModel_AudioMetricsHistogramBin(): + +class TestModel_AudioMetricsHistogramBin: """ Test Class for AudioMetricsHistogramBin """ @@ -4121,7 +4370,8 @@ def test_audio_metrics_histogram_bin_serialization(self): audio_metrics_histogram_bin_model_json2 = audio_metrics_histogram_bin_model.to_dict() assert audio_metrics_histogram_bin_model_json2 == audio_metrics_histogram_bin_model_json -class TestModel_AudioResource(): + +class TestModel_AudioResource: """ Test Class for AudioResource """ @@ -4133,7 +4383,7 @@ def test_audio_resource_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 @@ -4161,7 +4411,8 @@ def test_audio_resource_serialization(self): audio_resource_model_json2 = audio_resource_model.to_dict() assert audio_resource_model_json2 == audio_resource_model_json -class TestModel_AudioResources(): + +class TestModel_AudioResources: """ Test Class for AudioResources """ @@ -4173,13 +4424,13 @@ def test_audio_resources_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 audio_details_model['compression'] = 'zip' - audio_resource_model = {} # AudioResource + audio_resource_model = {} # AudioResource audio_resource_model['duration'] = 38 audio_resource_model['name'] = 'testString' audio_resource_model['details'] = audio_details_model @@ -4205,7 +4456,8 @@ def test_audio_resources_serialization(self): audio_resources_model_json2 = audio_resources_model.to_dict() assert audio_resources_model_json2 == audio_resources_model_json -class TestModel_Corpora(): + +class TestModel_Corpora: """ Test Class for Corpora """ @@ -4217,7 +4469,7 @@ def test_corpora_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - corpus_model = {} # Corpus + corpus_model = {} # Corpus corpus_model['name'] = 'testString' corpus_model['total_words'] = 38 corpus_model['out_of_vocabulary_words'] = 38 @@ -4243,7 +4495,8 @@ def test_corpora_serialization(self): corpora_model_json2 = corpora_model.to_dict() assert corpora_model_json2 == corpora_model_json -class TestModel_Corpus(): + +class TestModel_Corpus: """ Test Class for Corpus """ @@ -4276,7 +4529,8 @@ def test_corpus_serialization(self): corpus_model_json2 = corpus_model.to_dict() assert corpus_model_json2 == corpus_model_json -class TestModel_CustomWord(): + +class TestModel_CustomWord: """ Test Class for CustomWord """ @@ -4289,6 +4543,7 @@ def test_custom_word_serialization(self): # Construct a json representation of a CustomWord model custom_word_model_json = {} custom_word_model_json['word'] = 'testString' + custom_word_model_json['mapping_only'] = ['testString'] custom_word_model_json['sounds_like'] = ['testString'] custom_word_model_json['display_as'] = 'testString' @@ -4307,7 +4562,8 @@ def test_custom_word_serialization(self): custom_word_model_json2 = custom_word_model.to_dict() assert custom_word_model_json2 == custom_word_model_json -class TestModel_Grammar(): + +class TestModel_Grammar: """ Test Class for Grammar """ @@ -4339,7 +4595,8 @@ def test_grammar_serialization(self): grammar_model_json2 = grammar_model.to_dict() assert grammar_model_json2 == grammar_model_json -class TestModel_Grammars(): + +class TestModel_Grammars: """ Test Class for Grammars """ @@ -4351,7 +4608,7 @@ def test_grammars_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - grammar_model = {} # Grammar + grammar_model = {} # Grammar grammar_model['name'] = 'testString' grammar_model['out_of_vocabulary_words'] = 38 grammar_model['status'] = 'analyzed' @@ -4376,7 +4633,8 @@ def test_grammars_serialization(self): grammars_model_json2 = grammars_model.to_dict() assert grammars_model_json2 == grammars_model_json -class TestModel_KeywordResult(): + +class TestModel_KeywordResult: """ Test Class for KeywordResult """ @@ -4408,7 +4666,8 @@ def test_keyword_result_serialization(self): keyword_result_model_json2 = keyword_result_model.to_dict() assert keyword_result_model_json2 == keyword_result_model_json -class TestModel_LanguageModel(): + +class TestModel_LanguageModel: """ Test Class for LanguageModel """ @@ -4450,7 +4709,8 @@ def test_language_model_serialization(self): language_model_model_json2 = language_model_model.to_dict() assert language_model_model_json2 == language_model_model_json -class TestModel_LanguageModels(): + +class TestModel_LanguageModels: """ Test Class for LanguageModels """ @@ -4462,7 +4722,7 @@ def test_language_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - language_model_model = {} # LanguageModel + language_model_model = {} # LanguageModel language_model_model['customization_id'] = 'testString' language_model_model['created'] = 'testString' language_model_model['updated'] = 'testString' @@ -4497,7 +4757,8 @@ def test_language_models_serialization(self): language_models_model_json2 = language_models_model.to_dict() assert language_models_model_json2 == language_models_model_json -class TestModel_ProcessedAudio(): + +class TestModel_ProcessedAudio: """ Test Class for ProcessedAudio """ @@ -4529,7 +4790,8 @@ def test_processed_audio_serialization(self): processed_audio_model_json2 = processed_audio_model.to_dict() assert processed_audio_model_json2 == processed_audio_model_json -class TestModel_ProcessingMetrics(): + +class TestModel_ProcessingMetrics: """ Test Class for ProcessingMetrics """ @@ -4541,7 +4803,7 @@ def test_processing_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 @@ -4568,7 +4830,8 @@ def test_processing_metrics_serialization(self): processing_metrics_model_json2 = processing_metrics_model.to_dict() assert processing_metrics_model_json2 == processing_metrics_model_json -class TestModel_RecognitionJob(): + +class TestModel_RecognitionJob: """ Test Class for RecognitionJob """ @@ -4580,58 +4843,58 @@ def test_recognition_job_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4642,11 +4905,11 @@ def test_recognition_job_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model - speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] @@ -4680,7 +4943,8 @@ def test_recognition_job_serialization(self): recognition_job_model_json2 = recognition_job_model.to_dict() assert recognition_job_model_json2 == recognition_job_model_json -class TestModel_RecognitionJobs(): + +class TestModel_RecognitionJobs: """ Test Class for RecognitionJobs """ @@ -4692,58 +4956,58 @@ def test_recognition_jobs_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4754,11 +5018,11 @@ def test_recognition_jobs_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model - speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] @@ -4766,7 +5030,7 @@ def test_recognition_jobs_serialization(self): speech_recognition_results_model['audio_metrics'] = audio_metrics_model speech_recognition_results_model['warnings'] = ['testString'] - recognition_job_model = {} # RecognitionJob + recognition_job_model = {} # RecognitionJob recognition_job_model['id'] = 'testString' recognition_job_model['status'] = 'waiting' recognition_job_model['created'] = 'testString' @@ -4795,7 +5059,8 @@ def test_recognition_jobs_serialization(self): recognition_jobs_model_json2 = recognition_jobs_model.to_dict() assert recognition_jobs_model_json2 == recognition_jobs_model_json -class TestModel_RegisterStatus(): + +class TestModel_RegisterStatus: """ Test Class for RegisterStatus """ @@ -4825,7 +5090,8 @@ def test_register_status_serialization(self): register_status_model_json2 = register_status_model.to_dict() assert register_status_model_json2 == register_status_model_json -class TestModel_SpeakerLabelsResult(): + +class TestModel_SpeakerLabelsResult: """ Test Class for SpeakerLabelsResult """ @@ -4858,7 +5124,8 @@ def test_speaker_labels_result_serialization(self): speaker_labels_result_model_json2 = speaker_labels_result_model.to_dict() assert speaker_labels_result_model_json2 == speaker_labels_result_model_json -class TestModel_SpeechModel(): + +class TestModel_SpeechModel: """ Test Class for SpeechModel """ @@ -4870,7 +5137,7 @@ def test_speech_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True @@ -4900,7 +5167,8 @@ def test_speech_model_serialization(self): speech_model_model_json2 = speech_model_model.to_dict() assert speech_model_model_json2 == speech_model_model_json -class TestModel_SpeechModels(): + +class TestModel_SpeechModels: """ Test Class for SpeechModels """ @@ -4912,13 +5180,13 @@ def test_speech_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True supported_features_model['low_latency'] = True - speech_model_model = {} # SpeechModel + speech_model_model = {} # SpeechModel speech_model_model['name'] = 'testString' speech_model_model['language'] = 'testString' speech_model_model['rate'] = 38 @@ -4945,7 +5213,8 @@ def test_speech_models_serialization(self): speech_models_model_json2 = speech_models_model.to_dict() assert speech_models_model_json2 == speech_models_model_json -class TestModel_SpeechRecognitionAlternative(): + +class TestModel_SpeechRecognitionAlternative: """ Test Class for SpeechRecognitionAlternative """ @@ -4977,7 +5246,8 @@ def test_speech_recognition_alternative_serialization(self): speech_recognition_alternative_model_json2 = speech_recognition_alternative_model.to_dict() assert speech_recognition_alternative_model_json2 == speech_recognition_alternative_model_json -class TestModel_SpeechRecognitionResult(): + +class TestModel_SpeechRecognitionResult: """ Test Class for SpeechRecognitionResult """ @@ -4989,23 +5259,23 @@ def test_speech_recognition_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] @@ -5033,7 +5303,8 @@ def test_speech_recognition_result_serialization(self): speech_recognition_result_model_json2 = speech_recognition_result_model.to_dict() assert speech_recognition_result_model_json2 == speech_recognition_result_model_json -class TestModel_SpeechRecognitionResults(): + +class TestModel_SpeechRecognitionResults: """ Test Class for SpeechRecognitionResults """ @@ -5045,58 +5316,58 @@ def test_speech_recognition_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -5107,7 +5378,7 @@ def test_speech_recognition_results_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model @@ -5135,7 +5406,8 @@ def test_speech_recognition_results_serialization(self): speech_recognition_results_model_json2 = speech_recognition_results_model.to_dict() assert speech_recognition_results_model_json2 == speech_recognition_results_model_json -class TestModel_SupportedFeatures(): + +class TestModel_SupportedFeatures: """ Test Class for SupportedFeatures """ @@ -5167,7 +5439,8 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestModel_TrainingResponse(): + +class TestModel_TrainingResponse: """ Test Class for TrainingResponse """ @@ -5179,7 +5452,7 @@ def test_training_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_warning_model = {} # TrainingWarning + training_warning_model = {} # TrainingWarning training_warning_model['code'] = 'invalid_audio_files' training_warning_model['message'] = 'testString' @@ -5202,7 +5475,8 @@ def test_training_response_serialization(self): training_response_model_json2 = training_response_model.to_dict() assert training_response_model_json2 == training_response_model_json -class TestModel_TrainingWarning(): + +class TestModel_TrainingWarning: """ Test Class for TrainingWarning """ @@ -5232,7 +5506,8 @@ def test_training_warning_serialization(self): training_warning_model_json2 = training_warning_model.to_dict() assert training_warning_model_json2 == training_warning_model_json -class TestModel_Word(): + +class TestModel_Word: """ Test Class for Word """ @@ -5244,12 +5519,13 @@ def test_word_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_error_model = {} # WordError + word_error_model = {} # WordError word_error_model['element'] = 'testString' # Construct a json representation of a Word model word_model_json = {} word_model_json['word'] = 'testString' + word_model_json['mapping_only'] = ['testString'] word_model_json['sounds_like'] = ['testString'] word_model_json['display_as'] = 'testString' word_model_json['count'] = 38 @@ -5271,7 +5547,8 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestModel_WordAlternativeResult(): + +class TestModel_WordAlternativeResult: """ Test Class for WordAlternativeResult """ @@ -5301,7 +5578,8 @@ def test_word_alternative_result_serialization(self): word_alternative_result_model_json2 = word_alternative_result_model.to_dict() assert word_alternative_result_model_json2 == word_alternative_result_model_json -class TestModel_WordAlternativeResults(): + +class TestModel_WordAlternativeResults: """ Test Class for WordAlternativeResults """ @@ -5313,7 +5591,7 @@ def test_word_alternative_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' @@ -5338,7 +5616,8 @@ def test_word_alternative_results_serialization(self): word_alternative_results_model_json2 = word_alternative_results_model.to_dict() assert word_alternative_results_model_json2 == word_alternative_results_model_json -class TestModel_WordError(): + +class TestModel_WordError: """ Test Class for WordError """ @@ -5367,7 +5646,8 @@ def test_word_error_serialization(self): word_error_model_json2 = word_error_model.to_dict() assert word_error_model_json2 == word_error_model_json -class TestModel_Words(): + +class TestModel_Words: """ Test Class for Words """ @@ -5379,11 +5659,12 @@ def test_words_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_error_model = {} # WordError + word_error_model = {} # WordError word_error_model['element'] = 'testString' - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' + word_model['mapping_only'] = ['testString'] word_model['sounds_like'] = ['testString'] word_model['display_as'] = 'testString' word_model['count'] = 38 diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 9d3d8c25..26341c54 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -69,7 +68,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListVoices(): + +class TestListVoices: """ Test Class for list_voices """ @@ -82,16 +82,17 @@ def test_list_voices_all_params(self): # Set up mock url = preprocess_url('/v1/voices') mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_voices() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -105,7 +106,8 @@ def test_list_voices_all_params_with_retries(self): _service.disable_retries() self.test_list_voices_all_params() -class TestGetVoice(): + +class TestGetVoice: """ Test Class for get_voice """ @@ -116,30 +118,32 @@ def test_get_voice_all_params(self): get_voice() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' customization_id = 'testString' # Invoke method response = _service.get_voice( voice, customization_id=customization_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customization_id={}'.format(customization_id) in query_string @@ -158,21 +162,23 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' # Invoke method response = _service.get_voice( voice, - headers={} + headers={}, ) # Check for correct operation @@ -194,23 +200,25 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' # Pass in all but one required param and check for a ValueError req_param_dict = { "voice": voice, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_voice(**req_copy) @@ -223,6 +231,7 @@ def test_get_voice_value_error_with_retries(self): _service.disable_retries() self.test_get_voice_value_error() + # endregion ############################################################################## # End of Service: Voices @@ -233,7 +242,8 @@ def test_get_voice_value_error_with_retries(self): ############################################################################## # region -class TestSynthesize(): + +class TestSynthesize: """ Test Class for synthesize """ @@ -246,11 +256,13 @@ def test_synthesize_all_params(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -258,8 +270,8 @@ def test_synthesize_all_params(self): voice = 'en-US_MichaelV3Voice' customization_id = 'testString' spell_out_mode = 'default' - rate_percentage = 38 - pitch_percentage = 38 + rate_percentage = 0 + pitch_percentage = 0 # Invoke method response = _service.synthesize( @@ -270,14 +282,14 @@ def test_synthesize_all_params(self): spell_out_mode=spell_out_mode, rate_percentage=rate_percentage, pitch_percentage=pitch_percentage, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'voice={}'.format(voice) in query_string assert 'customization_id={}'.format(customization_id) in query_string @@ -305,11 +317,13 @@ def test_synthesize_required_params(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -317,7 +331,7 @@ def test_synthesize_required_params(self): # Invoke method response = _service.synthesize( text, - headers={} + headers={}, ) # Check for correct operation @@ -344,11 +358,13 @@ def test_synthesize_value_error(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -358,7 +374,7 @@ def test_synthesize_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.synthesize(**req_copy) @@ -371,6 +387,7 @@ def test_synthesize_value_error_with_retries(self): _service.disable_retries() self.test_synthesize_value_error() + # endregion ############################################################################## # End of Service: Synthesis @@ -381,7 +398,8 @@ def test_synthesize_value_error_with_retries(self): ############################################################################## # region -class TestGetPronunciation(): + +class TestGetPronunciation: """ Test Class for get_pronunciation """ @@ -394,11 +412,13 @@ def test_get_pronunciation_all_params(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -412,14 +432,14 @@ def test_get_pronunciation_all_params(self): voice=voice, format=format, customization_id=customization_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'text={}'.format(text) in query_string assert 'voice={}'.format(voice) in query_string @@ -443,11 +463,13 @@ def test_get_pronunciation_required_params(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -455,14 +477,14 @@ def test_get_pronunciation_required_params(self): # Invoke method response = _service.get_pronunciation( text, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'text={}'.format(text) in query_string @@ -483,11 +505,13 @@ def test_get_pronunciation_value_error(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -497,7 +521,7 @@ def test_get_pronunciation_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_pronunciation(**req_copy) @@ -510,6 +534,7 @@ def test_get_pronunciation_value_error_with_retries(self): _service.disable_retries() self.test_get_pronunciation_value_error() + # endregion ############################################################################## # End of Service: Pronunciation @@ -520,7 +545,8 @@ def test_get_pronunciation_value_error_with_retries(self): ############################################################################## # region -class TestCreateCustomModel(): + +class TestCreateCustomModel: """ Test Class for create_custom_model """ @@ -533,11 +559,13 @@ def test_create_custom_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -549,7 +577,7 @@ def test_create_custom_model_all_params(self): name, language=language, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -578,11 +606,13 @@ def test_create_custom_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -594,7 +624,7 @@ def test_create_custom_model_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_custom_model(**req_copy) @@ -607,7 +637,8 @@ def test_create_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_create_custom_model_value_error() -class TestListCustomModels(): + +class TestListCustomModels: """ Test Class for list_custom_models """ @@ -620,26 +651,28 @@ def test_list_custom_models_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - language = 'ar-MS' + language = 'de-DE' # Invoke method response = _service.list_custom_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -660,16 +693,17 @@ def test_list_custom_models_required_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_custom_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -683,7 +717,8 @@ def test_list_custom_models_required_params_with_retries(self): _service.disable_retries() self.test_list_custom_models_required_params() -class TestUpdateCustomModel(): + +class TestUpdateCustomModel: """ Test Class for update_custom_model """ @@ -695,9 +730,11 @@ def test_update_custom_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -717,7 +754,7 @@ def test_update_custom_model_all_params(self): name=name, description=description, words=words, - headers={} + headers={}, ) # Check for correct operation @@ -745,9 +782,11 @@ def test_update_custom_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -766,7 +805,7 @@ def test_update_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_custom_model(**req_copy) @@ -779,7 +818,8 @@ def test_update_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_update_custom_model_value_error() -class TestGetCustomModel(): + +class TestGetCustomModel: """ Test Class for get_custom_model """ @@ -792,11 +832,13 @@ def test_get_custom_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -804,7 +846,7 @@ def test_get_custom_model_all_params(self): # Invoke method response = _service.get_custom_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -828,11 +870,13 @@ def test_get_custom_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -842,7 +886,7 @@ def test_get_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_custom_model(**req_copy) @@ -855,7 +899,8 @@ def test_get_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_get_custom_model_value_error() -class TestDeleteCustomModel(): + +class TestDeleteCustomModel: """ Test Class for delete_custom_model """ @@ -867,9 +912,11 @@ def test_delete_custom_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -877,7 +924,7 @@ def test_delete_custom_model_all_params(self): # Invoke method response = _service.delete_custom_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -900,9 +947,11 @@ def test_delete_custom_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -912,7 +961,7 @@ def test_delete_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_custom_model(**req_copy) @@ -925,6 +974,7 @@ def test_delete_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_custom_model_value_error() + # endregion ############################################################################## # End of Service: CustomModels @@ -935,7 +985,8 @@ def test_delete_custom_model_value_error_with_retries(self): ############################################################################## # region -class TestAddWords(): + +class TestAddWords: """ Test Class for add_words """ @@ -947,9 +998,11 @@ def test_add_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -965,7 +1018,7 @@ def test_add_words_all_params(self): response = _service.add_words( customization_id, words, - headers={} + headers={}, ) # Check for correct operation @@ -991,9 +1044,11 @@ def test_add_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -1011,7 +1066,7 @@ def test_add_words_value_error(self): "words": words, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_words(**req_copy) @@ -1024,7 +1079,8 @@ def test_add_words_value_error_with_retries(self): _service.disable_retries() self.test_add_words_value_error() -class TestListWords(): + +class TestListWords: """ Test Class for list_words """ @@ -1037,11 +1093,13 @@ def test_list_words_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1049,7 +1107,7 @@ def test_list_words_all_params(self): # Invoke method response = _service.list_words( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1073,11 +1131,13 @@ def test_list_words_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1087,7 +1147,7 @@ def test_list_words_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_words(**req_copy) @@ -1100,7 +1160,8 @@ def test_list_words_value_error_with_retries(self): _service.disable_retries() self.test_list_words_value_error() -class TestAddWord(): + +class TestAddWord: """ Test Class for add_word """ @@ -1112,9 +1173,11 @@ def test_add_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=200) + responses.add( + responses.PUT, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1128,7 +1191,7 @@ def test_add_word_all_params(self): word, translation, part_of_speech=part_of_speech, - headers={} + headers={}, ) # Check for correct operation @@ -1155,9 +1218,11 @@ def test_add_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=200) + responses.add( + responses.PUT, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1172,7 +1237,7 @@ def test_add_word_value_error(self): "translation": translation, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_word(**req_copy) @@ -1185,7 +1250,8 @@ def test_add_word_value_error_with_retries(self): _service.disable_retries() self.test_add_word_value_error() -class TestGetWord(): + +class TestGetWord: """ Test Class for get_word """ @@ -1198,11 +1264,13 @@ def test_get_word_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1212,7 +1280,7 @@ def test_get_word_all_params(self): response = _service.get_word( customization_id, word, - headers={} + headers={}, ) # Check for correct operation @@ -1236,11 +1304,13 @@ def test_get_word_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1252,7 +1322,7 @@ def test_get_word_value_error(self): "word": word, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_word(**req_copy) @@ -1265,7 +1335,8 @@ def test_get_word_value_error_with_retries(self): _service.disable_retries() self.test_get_word_value_error() -class TestDeleteWord(): + +class TestDeleteWord: """ Test Class for delete_word """ @@ -1277,9 +1348,11 @@ def test_delete_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1289,7 +1362,7 @@ def test_delete_word_all_params(self): response = _service.delete_word( customization_id, word, - headers={} + headers={}, ) # Check for correct operation @@ -1312,9 +1385,11 @@ def test_delete_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1326,7 +1401,7 @@ def test_delete_word_value_error(self): "word": word, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_word(**req_copy) @@ -1339,6 +1414,7 @@ def test_delete_word_value_error_with_retries(self): _service.disable_retries() self.test_delete_word_value_error() + # endregion ############################################################################## # End of Service: CustomWords @@ -1349,7 +1425,8 @@ def test_delete_word_value_error_with_retries(self): ############################################################################## # region -class TestListCustomPrompts(): + +class TestListCustomPrompts: """ Test Class for list_custom_prompts """ @@ -1362,11 +1439,13 @@ def test_list_custom_prompts_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1374,7 +1453,7 @@ def test_list_custom_prompts_all_params(self): # Invoke method response = _service.list_custom_prompts( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1398,11 +1477,13 @@ def test_list_custom_prompts_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1412,7 +1493,7 @@ def test_list_custom_prompts_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_custom_prompts(**req_copy) @@ -1425,7 +1506,8 @@ def test_list_custom_prompts_value_error_with_retries(self): _service.disable_retries() self.test_list_custom_prompts_value_error() -class TestAddCustomPrompt(): + +class TestAddCustomPrompt: """ Test Class for add_custom_prompt """ @@ -1438,11 +1520,13 @@ def test_add_custom_prompt_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a PromptMetadata model prompt_metadata_model = {} @@ -1461,7 +1545,7 @@ def test_add_custom_prompt_all_params(self): prompt_id, metadata, file, - headers={} + headers={}, ) # Check for correct operation @@ -1485,11 +1569,13 @@ def test_add_custom_prompt_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a PromptMetadata model prompt_metadata_model = {} @@ -1510,7 +1596,7 @@ def test_add_custom_prompt_value_error(self): "file": file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_custom_prompt(**req_copy) @@ -1523,7 +1609,8 @@ def test_add_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_add_custom_prompt_value_error() -class TestGetCustomPrompt(): + +class TestGetCustomPrompt: """ Test Class for get_custom_prompt """ @@ -1536,11 +1623,13 @@ def test_get_custom_prompt_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1550,7 +1639,7 @@ def test_get_custom_prompt_all_params(self): response = _service.get_custom_prompt( customization_id, prompt_id, - headers={} + headers={}, ) # Check for correct operation @@ -1574,11 +1663,13 @@ def test_get_custom_prompt_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1590,7 +1681,7 @@ def test_get_custom_prompt_value_error(self): "prompt_id": prompt_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_custom_prompt(**req_copy) @@ -1603,7 +1694,8 @@ def test_get_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_get_custom_prompt_value_error() -class TestDeleteCustomPrompt(): + +class TestDeleteCustomPrompt: """ Test Class for delete_custom_prompt """ @@ -1615,9 +1707,11 @@ def test_delete_custom_prompt_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1627,7 +1721,7 @@ def test_delete_custom_prompt_all_params(self): response = _service.delete_custom_prompt( customization_id, prompt_id, - headers={} + headers={}, ) # Check for correct operation @@ -1650,9 +1744,11 @@ def test_delete_custom_prompt_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1664,7 +1760,7 @@ def test_delete_custom_prompt_value_error(self): "prompt_id": prompt_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_custom_prompt(**req_copy) @@ -1677,6 +1773,7 @@ def test_delete_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_delete_custom_prompt_value_error() + # endregion ############################################################################## # End of Service: CustomPrompts @@ -1687,7 +1784,8 @@ def test_delete_custom_prompt_value_error_with_retries(self): ############################################################################## # region -class TestListSpeakerModels(): + +class TestListSpeakerModels: """ Test Class for list_speaker_models """ @@ -1700,16 +1798,17 @@ def test_list_speaker_models_all_params(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speakers": [{"speaker_id": "speaker_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_speaker_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1723,7 +1822,8 @@ def test_list_speaker_models_all_params_with_retries(self): _service.disable_retries() self.test_list_speaker_models_all_params() -class TestCreateSpeakerModel(): + +class TestCreateSpeakerModel: """ Test Class for create_speaker_model """ @@ -1736,11 +1836,13 @@ def test_create_speaker_model_all_params(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values speaker_name = 'testString' @@ -1750,14 +1852,14 @@ def test_create_speaker_model_all_params(self): response = _service.create_speaker_model( speaker_name, audio, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'speaker_name={}'.format(speaker_name) in query_string # Validate body params @@ -1780,11 +1882,13 @@ def test_create_speaker_model_value_error(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values speaker_name = 'testString' @@ -1796,7 +1900,7 @@ def test_create_speaker_model_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_speaker_model(**req_copy) @@ -1809,7 +1913,8 @@ def test_create_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_create_speaker_model_value_error() -class TestGetSpeakerModel(): + +class TestGetSpeakerModel: """ Test Class for get_speaker_model """ @@ -1822,11 +1927,13 @@ def test_get_speaker_model_all_params(self): # Set up mock url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values speaker_id = 'testString' @@ -1834,7 +1941,7 @@ def test_get_speaker_model_all_params(self): # Invoke method response = _service.get_speaker_model( speaker_id, - headers={} + headers={}, ) # Check for correct operation @@ -1858,11 +1965,13 @@ def test_get_speaker_model_value_error(self): # Set up mock url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values speaker_id = 'testString' @@ -1872,7 +1981,7 @@ def test_get_speaker_model_value_error(self): "speaker_id": speaker_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_speaker_model(**req_copy) @@ -1885,7 +1994,8 @@ def test_get_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_get_speaker_model_value_error() -class TestDeleteSpeakerModel(): + +class TestDeleteSpeakerModel: """ Test Class for delete_speaker_model """ @@ -1897,9 +2007,11 @@ def test_delete_speaker_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/speakers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values speaker_id = 'testString' @@ -1907,7 +2019,7 @@ def test_delete_speaker_model_all_params(self): # Invoke method response = _service.delete_speaker_model( speaker_id, - headers={} + headers={}, ) # Check for correct operation @@ -1930,9 +2042,11 @@ def test_delete_speaker_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/speakers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values speaker_id = 'testString' @@ -1942,7 +2056,7 @@ def test_delete_speaker_model_value_error(self): "speaker_id": speaker_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_speaker_model(**req_copy) @@ -1955,6 +2069,7 @@ def test_delete_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_speaker_model_value_error() + # endregion ############################################################################## # End of Service: SpeakerModels @@ -1965,7 +2080,8 @@ def test_delete_speaker_model_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -1977,9 +2093,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -1987,14 +2105,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -2014,9 +2132,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -2026,7 +2146,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -2039,6 +2159,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -2049,7 +2170,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_CustomModel(): + + +class TestModel_CustomModel: """ Test Class for CustomModel """ @@ -2061,12 +2184,12 @@ def test_custom_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' @@ -2100,7 +2223,8 @@ def test_custom_model_serialization(self): custom_model_model_json2 = custom_model_model.to_dict() assert custom_model_model_json2 == custom_model_model_json -class TestModel_CustomModels(): + +class TestModel_CustomModels: """ Test Class for CustomModels """ @@ -2112,19 +2236,19 @@ def test_custom_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2154,7 +2278,8 @@ def test_custom_models_serialization(self): custom_models_model_json2 = custom_models_model.to_dict() assert custom_models_model_json2 == custom_models_model_json -class TestModel_Prompt(): + +class TestModel_Prompt: """ Test Class for Prompt """ @@ -2187,7 +2312,8 @@ def test_prompt_serialization(self): prompt_model_json2 = prompt_model.to_dict() assert prompt_model_json2 == prompt_model_json -class TestModel_PromptMetadata(): + +class TestModel_PromptMetadata: """ Test Class for PromptMetadata """ @@ -2217,7 +2343,8 @@ def test_prompt_metadata_serialization(self): prompt_metadata_model_json2 = prompt_metadata_model.to_dict() assert prompt_metadata_model_json2 == prompt_metadata_model_json -class TestModel_Prompts(): + +class TestModel_Prompts: """ Test Class for Prompts """ @@ -2229,7 +2356,7 @@ def test_prompts_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' @@ -2255,7 +2382,8 @@ def test_prompts_serialization(self): prompts_model_json2 = prompts_model.to_dict() assert prompts_model_json2 == prompts_model_json -class TestModel_Pronunciation(): + +class TestModel_Pronunciation: """ Test Class for Pronunciation """ @@ -2284,7 +2412,8 @@ def test_pronunciation_serialization(self): pronunciation_model_json2 = pronunciation_model.to_dict() assert pronunciation_model_json2 == pronunciation_model_json -class TestModel_Speaker(): + +class TestModel_Speaker: """ Test Class for Speaker """ @@ -2314,7 +2443,8 @@ def test_speaker_serialization(self): speaker_model_json2 = speaker_model.to_dict() assert speaker_model_json2 == speaker_model_json -class TestModel_SpeakerCustomModel(): + +class TestModel_SpeakerCustomModel: """ Test Class for SpeakerCustomModel """ @@ -2326,7 +2456,7 @@ def test_speaker_custom_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model = {} # SpeakerPrompt speaker_prompt_model['prompt'] = 'testString' speaker_prompt_model['prompt_id'] = 'testString' speaker_prompt_model['status'] = 'testString' @@ -2352,7 +2482,8 @@ def test_speaker_custom_model_serialization(self): speaker_custom_model_model_json2 = speaker_custom_model_model.to_dict() assert speaker_custom_model_model_json2 == speaker_custom_model_model_json -class TestModel_SpeakerCustomModels(): + +class TestModel_SpeakerCustomModels: """ Test Class for SpeakerCustomModels """ @@ -2364,13 +2495,13 @@ def test_speaker_custom_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model = {} # SpeakerPrompt speaker_prompt_model['prompt'] = 'testString' speaker_prompt_model['prompt_id'] = 'testString' speaker_prompt_model['status'] = 'testString' speaker_prompt_model['error'] = 'testString' - speaker_custom_model_model = {} # SpeakerCustomModel + speaker_custom_model_model = {} # SpeakerCustomModel speaker_custom_model_model['customization_id'] = 'testString' speaker_custom_model_model['prompts'] = [speaker_prompt_model] @@ -2393,7 +2524,8 @@ def test_speaker_custom_models_serialization(self): speaker_custom_models_model_json2 = speaker_custom_models_model.to_dict() assert speaker_custom_models_model_json2 == speaker_custom_models_model_json -class TestModel_SpeakerModel(): + +class TestModel_SpeakerModel: """ Test Class for SpeakerModel """ @@ -2422,7 +2554,8 @@ def test_speaker_model_serialization(self): speaker_model_model_json2 = speaker_model_model.to_dict() assert speaker_model_model_json2 == speaker_model_model_json -class TestModel_SpeakerPrompt(): + +class TestModel_SpeakerPrompt: """ Test Class for SpeakerPrompt """ @@ -2454,7 +2587,8 @@ def test_speaker_prompt_serialization(self): speaker_prompt_model_json2 = speaker_prompt_model.to_dict() assert speaker_prompt_model_json2 == speaker_prompt_model_json -class TestModel_Speakers(): + +class TestModel_Speakers: """ Test Class for Speakers """ @@ -2466,7 +2600,7 @@ def test_speakers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_model = {} # Speaker + speaker_model = {} # Speaker speaker_model['speaker_id'] = 'testString' speaker_model['name'] = 'testString' @@ -2489,7 +2623,8 @@ def test_speakers_serialization(self): speakers_model_json2 = speakers_model.to_dict() assert speakers_model_json2 == speakers_model_json -class TestModel_SupportedFeatures(): + +class TestModel_SupportedFeatures: """ Test Class for SupportedFeatures """ @@ -2519,7 +2654,8 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestModel_Translation(): + +class TestModel_Translation: """ Test Class for Translation """ @@ -2549,7 +2685,8 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestModel_Voice(): + +class TestModel_Voice: """ Test Class for Voice """ @@ -2561,23 +2698,23 @@ def test_voice_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_pronunciation'] = True supported_features_model['voice_transformation'] = True - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2614,7 +2751,8 @@ def test_voice_serialization(self): voice_model_json2 = voice_model.to_dict() assert voice_model_json2 == voice_model_json -class TestModel_Voices(): + +class TestModel_Voices: """ Test Class for Voices """ @@ -2626,23 +2764,23 @@ def test_voices_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_pronunciation'] = True supported_features_model['voice_transformation'] = True - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2653,7 +2791,7 @@ def test_voices_serialization(self): custom_model_model['words'] = [word_model] custom_model_model['prompts'] = [prompt_model] - voice_model = {} # Voice + voice_model = {} # Voice voice_model['url'] = 'testString' voice_model['gender'] = 'testString' voice_model['name'] = 'testString' @@ -2682,7 +2820,8 @@ def test_voices_serialization(self): voices_model_json2 = voices_model.to_dict() assert voices_model_json2 == voices_model_json -class TestModel_Word(): + +class TestModel_Word: """ Test Class for Word """ @@ -2713,7 +2852,8 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestModel_Words(): + +class TestModel_Words: """ Test Class for Words """ @@ -2725,7 +2865,7 @@ def test_words_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi'