From 6e8e10077d894126fb10f5717da1d7063f93f9e2 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 24 Nov 2019 04:22:25 +0100 Subject: [PATCH 01/28] Travis CI: Python cache is pip, not pip3 --- .travis.yml | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index b32f1e8e7..f9b57df0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,12 @@ language: python -matrix: - include: - - python: 3.5 - - python: 3.6 - - python: 3.7 - - python: 3.8 +python: + - 3.5 + - 3.6 + - 3.7 + - 3.8 -cache: pip3 +cache: pip before_install: - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_cebf25e6c525_key @@ -27,10 +26,9 @@ script: - tox before_deploy: +- pip3 install bumpversion pypandoc - sudo apt-get update -- pip3 install pypandoc - sudo apt-get install pandoc -- pip3 install bumpversion - nvm install 12 - npm install @semantic-release/changelog - npm install @semantic-release/exec @@ -42,13 +40,13 @@ deploy: script: docs/publish.sh skip_cleanup: true on: - python: '3.5' + python: 3.8 tags: true - provider: script script: npx semantic-release skip_cleanup: true on: - python: '3.5' + python: 3.8 branch: master - provider: pypi user: watson-devex @@ -56,5 +54,5 @@ deploy: repository: https://upload.pypi.org/legacy skip_cleanup: true on: - python: '3.5' + python: 3.8 tags: true From ffa787178210f5ef2959d34ff6107175a27616b1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 19 Dec 2019 02:57:47 -0500 Subject: [PATCH 02/28] doc(ltv3): Add examples for document translation methods --- examples/language_translator_v3.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index 2cced01c4..12feb0b1d 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -43,3 +43,32 @@ # # Get model details # model = language_translator.get_model(model_id='').get_result() # print(json.dumps(model, indent=2)) + +#### Document Translation #### +# List Documents +result = language_translator.list_documents().get_result() +print(json.dumps(result, indent=2)) + +# Translate Document +with open('en.pdf', 'rb') as file: + result = language_translator.translate_document( + file=file, + file_content_type='application/pdf', + filename='en.pdf', + model_id='en-fr').get_result() + print(json.dumps(result, indent=2)) + +# Document Status +result = language_translator.get_document_status( + document_id='{document id}').get_result() +print(json.dumps(result, indent=2)) + +# Translated Document +with open('translated.pdf', 'wb') as f: + result = language_translator.get_translated_document( + document_id='{document id}', + accept='application/pdf').get_result() + f.write(result.content) + +# Delete Document +language_translator.delete_document(document_id='{document id}') From 97286d33b362928ca67e50f6af71891ce3d983e3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:31:36 -0500 Subject: [PATCH 03/28] refactor(assssistantv1): Regenerate assistantv1 --- ibm_watson/assistant_v1.py | 2791 ++++++++++------- test/unit/test_assistant_v1.py | 5131 ++++++++++++++++++++++---------- 2 files changed, 5286 insertions(+), 2636 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index c93fc3ada..393be33e2 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,12 +22,17 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -37,13 +42,15 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Assistant service. @@ -62,40 +69,30 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('assistant') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('assistant') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Message ######################### def message(self, - workspace_id, + workspace_id: str, *, - input=None, - intents=None, - entities=None, - alternate_intents=None, - context=None, - output=None, - nodes_visited_details=None, - **kwargs): + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + alternate_intents: bool = None, + context: 'Context' = None, + output: 'OutputData' = None, + nodes_visited_details: bool = None, + **kwargs) -> 'DetailedResponse': """ Get response to user input. @@ -109,11 +106,11 @@ def message(self, :param str workspace_id: Unique identifier of the workspace. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :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 + :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. @@ -148,7 +145,9 @@ def message(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'message') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='message') headers.update(sdk_headers) params = { @@ -171,8 +170,8 @@ def message(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -182,11 +181,11 @@ def message(self, def list_workspaces(self, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List workspaces. @@ -211,7 +210,9 @@ def list_workspaces(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -226,25 +227,25 @@ def list_workspaces(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_workspace(self, *, - name=None, - description=None, - language=None, - metadata=None, - learning_opt_out=None, - system_settings=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None, - **kwargs): + name: str = None, + description: str = None, + language: str = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None, + **kwargs) -> 'DetailedResponse': """ Create workspace. @@ -265,15 +266,15 @@ def create_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :param list[CreateIntent] intents: (optional) An array of objects defining + :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. - :param list[CreateEntity] entities: (optional) An array of objects + :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param 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. - :param list[Webhook] webhooks: (optional) + :param List[Webhook] webhooks: (optional) :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -295,7 +296,9 @@ def create_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -319,18 +322,18 @@ def create_workspace(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_workspace(self, - workspace_id, + workspace_id: str, *, - export=None, - include_audit=None, - sort=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + sort: str = None, + **kwargs) -> 'DetailedResponse': """ Get information about a workspace. @@ -361,7 +364,9 @@ def get_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -375,27 +380,27 @@ def get_workspace(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_workspace(self, - workspace_id, + workspace_id: str, *, - name=None, - description=None, - language=None, - metadata=None, - learning_opt_out=None, - system_settings=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None, - append=None, - **kwargs): + name: str = None, + description: str = None, + language: str = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None, + append: bool = None, + **kwargs) -> 'DetailedResponse': """ Update workspace. @@ -417,15 +422,15 @@ def update_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :param list[CreateIntent] intents: (optional) An array of objects defining + :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. - :param list[CreateEntity] entities: (optional) An array of objects + :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param 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. - :param list[Webhook] webhooks: (optional) + :param List[Webhook] webhooks: (optional) :param bool append: (optional) Whether the new data is to be appended to the existing data in the workspace. If **append**=`false`, elements included in the new data completely replace the corresponding existing @@ -458,7 +463,9 @@ def update_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version, 'append': append} @@ -482,12 +489,13 @@ def update_workspace(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_workspace(self, workspace_id, **kwargs): + def delete_workspace(self, workspace_id: str, + **kwargs) -> 'DetailedResponse': """ Delete workspace. @@ -507,7 +515,9 @@ def delete_workspace(self, workspace_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -516,8 +526,8 @@ def delete_workspace(self, workspace_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -526,14 +536,14 @@ def delete_workspace(self, workspace_id, **kwargs): ######################### def list_intents(self, - workspace_id, + workspace_id: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List intents. @@ -567,7 +577,9 @@ def list_intents(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -584,18 +596,18 @@ def list_intents(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - description=None, - examples=None, - **kwargs): + description: str = None, + examples: List['Example'] = None, + **kwargs) -> 'DetailedResponse': """ Create intent. @@ -613,7 +625,7 @@ def create_intent(self, - It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -630,7 +642,9 @@ def create_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -647,18 +661,18 @@ def create_intent(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get intent. @@ -688,7 +702,9 @@ def get_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -702,19 +718,19 @@ def get_intent(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - new_intent=None, - new_description=None, - new_examples=None, - **kwargs): + new_intent: str = None, + new_description: str = None, + new_examples: List['Example'] = None, + **kwargs) -> 'DetailedResponse': """ Update intent. @@ -734,7 +750,7 @@ def update_intent(self, - It cannot begin with the reserved prefix `sys-`. :param str new_description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param list[Example] new_examples: (optional) An array of user input + :param List[Example] new_examples: (optional) An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -751,7 +767,9 @@ def update_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -768,12 +786,13 @@ def update_intent(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_intent(self, workspace_id, intent, **kwargs): + def delete_intent(self, workspace_id: str, intent: str, + **kwargs) -> 'DetailedResponse': """ Delete intent. @@ -796,7 +815,9 @@ def delete_intent(self, workspace_id, intent, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -806,8 +827,8 @@ def delete_intent(self, workspace_id, intent, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -816,14 +837,14 @@ def delete_intent(self, workspace_id, intent, **kwargs): ######################### def list_examples(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List user input examples. @@ -856,7 +877,9 @@ def list_examples(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -872,18 +895,18 @@ def list_examples(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - mentions=None, - **kwargs): + mentions: List['Mention'] = None, + **kwargs) -> 'DetailedResponse': """ Create user input example. @@ -899,7 +922,7 @@ def create_example(self, to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] mentions: (optional) An array of contextual entity + :param List[Mention] mentions: (optional) An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -918,7 +941,9 @@ def create_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -931,18 +956,18 @@ def create_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get user input example. @@ -970,7 +995,9 @@ def get_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version, 'include_audit': include_audit} @@ -980,19 +1007,19 @@ def get_example(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - new_text=None, - new_mentions=None, - **kwargs): + new_text: str = None, + new_mentions: List['Mention'] = None, + **kwargs) -> 'DetailedResponse': """ Update user input example. @@ -1009,7 +1036,7 @@ def update_example(self, string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] new_mentions: (optional) An array of contextual entity + :param List[Mention] new_mentions: (optional) An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1028,7 +1055,9 @@ def update_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1041,12 +1070,13 @@ def update_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_example(self, workspace_id, intent, text, **kwargs): + def delete_example(self, workspace_id: str, intent: str, text: str, + **kwargs) -> 'DetailedResponse': """ Delete user input example. @@ -1072,7 +1102,9 @@ def delete_example(self, workspace_id, intent, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1082,8 +1114,8 @@ def delete_example(self, workspace_id, intent, text, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1092,13 +1124,13 @@ def delete_example(self, workspace_id, intent, text, **kwargs): ######################### def list_counterexamples(self, - workspace_id, + workspace_id: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List counterexamples. @@ -1128,8 +1160,9 @@ def list_counterexamples(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = { @@ -1145,12 +1178,13 @@ def list_counterexamples(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_counterexample(self, workspace_id, text, **kwargs): + def create_counterexample(self, workspace_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Create counterexample. @@ -1179,8 +1213,9 @@ def create_counterexample(self, workspace_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -1193,17 +1228,17 @@ def create_counterexample(self, workspace_id, text, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_counterexample(self, - workspace_id, - text, + workspace_id: str, + text: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get counterexample. @@ -1230,8 +1265,9 @@ def get_counterexample(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version, 'include_audit': include_audit} @@ -1241,17 +1277,17 @@ def get_counterexample(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_counterexample(self, - workspace_id, - text, + workspace_id: str, + text: str, *, - new_text=None, - **kwargs): + new_text: str = None, + **kwargs) -> 'DetailedResponse': """ Update counterexample. @@ -1282,8 +1318,9 @@ def update_counterexample(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -1296,12 +1333,13 @@ def update_counterexample(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_counterexample(self, workspace_id, text, **kwargs): + def delete_counterexample(self, workspace_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Delete counterexample. @@ -1326,8 +1364,9 @@ def delete_counterexample(self, workspace_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -1337,8 +1376,8 @@ def delete_counterexample(self, workspace_id, text, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1347,14 +1386,14 @@ def delete_counterexample(self, workspace_id, text, **kwargs): ######################### def list_entities(self, - workspace_id, + workspace_id: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entities. @@ -1388,7 +1427,9 @@ def list_entities(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -1405,20 +1446,20 @@ def list_entities(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - values=None, - **kwargs): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + values: List['CreateValue'] = None, + **kwargs) -> 'DetailedResponse': """ Create entity. @@ -1441,7 +1482,7 @@ def create_entity(self, :param dict metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param list[CreateValue] values: (optional) An array of objects describing + :param List[CreateValue] values: (optional) An array of objects describing the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1458,7 +1499,9 @@ def create_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1477,18 +1520,18 @@ def create_entity(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity. @@ -1518,7 +1561,9 @@ def get_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -1532,21 +1577,21 @@ def get_entity(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - new_entity=None, - new_description=None, - new_metadata=None, - new_fuzzy_match=None, - new_values=None, - **kwargs): + new_entity: str = None, + new_description: str = None, + new_metadata: dict = None, + new_fuzzy_match: bool = None, + new_values: List['CreateValue'] = None, + **kwargs) -> 'DetailedResponse': """ Update entity. @@ -1569,7 +1614,7 @@ def update_entity(self, :param dict new_metadata: (optional) Any metadata related to the entity. :param bool new_fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param list[CreateValue] new_values: (optional) An array of objects + :param List[CreateValue] new_values: (optional) An array of objects describing the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1586,7 +1631,9 @@ def update_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1605,12 +1652,13 @@ def update_entity(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_entity(self, workspace_id, entity, **kwargs): + def delete_entity(self, workspace_id: str, entity: str, + **kwargs) -> 'DetailedResponse': """ Delete entity. @@ -1633,7 +1681,9 @@ def delete_entity(self, workspace_id, entity, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1643,8 +1693,8 @@ def delete_entity(self, workspace_id, entity, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1653,12 +1703,12 @@ def delete_entity(self, workspace_id, entity, **kwargs): ######################### def list_mentions(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity mentions. @@ -1688,7 +1738,9 @@ def list_mentions(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -1702,8 +1754,8 @@ def list_mentions(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1712,15 +1764,15 @@ def list_mentions(self, ######################### def list_values(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity values. @@ -1756,7 +1808,9 @@ def list_values(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -1773,21 +1827,21 @@ def list_values(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - metadata=None, - type=None, - synonyms=None, - patterns=None, - **kwargs): + metadata: dict = None, + type: str = None, + synonyms: List[str] = None, + patterns: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Create entity value. @@ -1805,13 +1859,13 @@ def create_value(self, - It cannot consist of only whitespace characters. :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 + :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. - :param list[str] patterns: (optional) An array of patterns for the entity + :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 @@ -1831,7 +1885,9 @@ def create_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1850,19 +1906,19 @@ def create_value(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity value. @@ -1894,7 +1950,9 @@ def get_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -1908,22 +1966,22 @@ def get_value(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - new_value=None, - new_metadata=None, - new_type=None, - new_synonyms=None, - new_patterns=None, - **kwargs): + new_value: str = None, + new_metadata: dict = None, + new_type: str = None, + new_synonyms: List[str] = None, + new_patterns: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Update entity value. @@ -1944,13 +2002,13 @@ def update_value(self, :param dict new_metadata: (optional) Any metadata related to the entity value. :param str new_type: (optional) Specifies the type of entity value. - :param list[str] new_synonyms: (optional) An array of synonyms for the + :param List[str] new_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. - :param list[str] new_patterns: (optional) An array of patterns for the + :param List[str] new_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 @@ -1970,7 +2028,9 @@ def update_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -1989,12 +2049,13 @@ def update_value(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_value(self, workspace_id, entity, value, **kwargs): + def delete_value(self, workspace_id: str, entity: str, value: str, + **kwargs) -> 'DetailedResponse': """ Delete entity value. @@ -2020,7 +2081,9 @@ def delete_value(self, workspace_id, entity, value, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -2030,8 +2093,8 @@ def delete_value(self, workspace_id, entity, value, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2040,15 +2103,15 @@ def delete_value(self, workspace_id, entity, value, **kwargs): ######################### def list_synonyms(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity value synonyms. @@ -2083,7 +2146,9 @@ def list_synonyms(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -2099,12 +2164,13 @@ def list_synonyms(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): + def create_synonym(self, workspace_id: str, entity: str, value: str, + synonym: str, **kwargs) -> 'DetailedResponse': """ Create entity value synonym. @@ -2139,7 +2205,9 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -2152,19 +2220,19 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_synonym(self, - workspace_id, - entity, - value, - synonym, + workspace_id: str, + entity: str, + value: str, + synonym: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity value synonym. @@ -2195,7 +2263,9 @@ def get_synonym(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version, 'include_audit': include_audit} @@ -2205,19 +2275,19 @@ def get_synonym(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_synonym(self, - workspace_id, - entity, - value, - synonym, + workspace_id: str, + entity: str, + value: str, + synonym: str, *, - new_synonym=None, - **kwargs): + new_synonym: str = None, + **kwargs) -> 'DetailedResponse': """ Update entity value synonym. @@ -2253,7 +2323,9 @@ def update_synonym(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -2266,12 +2338,13 @@ def update_synonym(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): + def delete_synonym(self, workspace_id: str, entity: str, value: str, + synonym: str, **kwargs) -> 'DetailedResponse': """ Delete entity value synonym. @@ -2300,7 +2373,9 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version} @@ -2310,8 +2385,8 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2320,13 +2395,13 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): ######################### def list_dialog_nodes(self, - workspace_id, + workspace_id: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List dialog nodes. @@ -2355,7 +2430,9 @@ def list_dialog_nodes(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -2371,34 +2448,34 @@ def list_dialog_nodes(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - description=None, - conditions=None, - parent=None, - previous_sibling=None, - output=None, - context=None, - metadata=None, - next_step=None, - title=None, - type=None, - event_name=None, - variable=None, - actions=None, - digress_in=None, - digress_out=None, - digress_out_slots=None, - user_label=None, - disambiguation_opt_out=None, - **kwargs): + description: str = None, + conditions: str = None, + parent: str = None, + previous_sibling: str = None, + output: 'DialogNodeOutput' = None, + context: dict = 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, + **kwargs) -> 'DetailedResponse': """ Create dialog node. @@ -2438,7 +2515,7 @@ def create_dialog_node(self, :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. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -2469,8 +2546,9 @@ def create_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -2503,17 +2581,17 @@ def create_dialog_node(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get dialog node. @@ -2538,7 +2616,9 @@ def get_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version, 'include_audit': include_audit} @@ -2548,35 +2628,35 @@ def get_dialog_node(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - new_dialog_node=None, - new_description=None, - new_conditions=None, - new_parent=None, - new_previous_sibling=None, - new_output=None, - new_context=None, - new_metadata=None, - new_next_step=None, - new_title=None, - new_type=None, - new_event_name=None, - new_variable=None, - new_actions=None, - new_digress_in=None, - new_digress_out=None, - new_digress_out_slots=None, - new_user_label=None, - new_disambiguation_opt_out=None, - **kwargs): + 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: dict = 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, + **kwargs) -> 'DetailedResponse': """ Update dialog node. @@ -2618,7 +2698,7 @@ def update_dialog_node(self, processed. :param str new_variable: (optional) The location in the dialog context where output is stored. - :param list[DialogNodeAction] new_actions: (optional) An array of objects + :param List[DialogNodeAction] new_actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str new_digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -2649,8 +2729,9 @@ def update_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -2683,12 +2764,13 @@ def update_dialog_node(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): + def delete_dialog_node(self, workspace_id: str, dialog_node: str, + **kwargs) -> 'DetailedResponse': """ Delete dialog node. @@ -2711,8 +2793,9 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - '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 = {'version': self.version} @@ -2722,8 +2805,8 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2732,13 +2815,13 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): ######################### def list_logs(self, - workspace_id, + workspace_id: str, *, - sort=None, - filter=None, - page_limit=None, - cursor=None, - **kwargs): + sort: str = None, + filter: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': """ List log events in a workspace. @@ -2769,7 +2852,9 @@ def list_logs(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -2785,18 +2870,18 @@ def list_logs(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def list_all_logs(self, - filter, + filter: str, *, - sort=None, - page_limit=None, - cursor=None, - **kwargs): + sort: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': """ List log events in all workspaces. @@ -2829,7 +2914,9 @@ def list_all_logs(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = { @@ -2844,8 +2931,8 @@ def list_all_logs(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2853,7 +2940,8 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -2863,6 +2951,8 @@ def delete_user_data(self, customer_id, **kwargs): with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://cloud.ibm.com/docs/services/assistant?topic=assistant-information-security#information-security). + This operation is limited to 4 requests per minute. For more information, see + **Rate limiting**. :param str customer_id: The customer ID for which all data is to be deleted. @@ -2877,7 +2967,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', '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 = {'version': self.version, 'customer_id': customer_id} @@ -2886,8 +2978,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3001,23 +3093,23 @@ 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 + :attr 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, *, location=None): + def __init__(self, group: str, *, location: List[int] = None) -> None: """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} valid_keys = ['group', 'location'] @@ -3035,7 +3127,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup 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, 'group') and self.group is not None: @@ -3044,17 +3141,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CaptureGroup') -> 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): + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3072,10 +3173,10 @@ class Context(): def __init__(self, *, - conversation_id=None, - system=None, - metadata=None, - **kwargs): + conversation_id: str = None, + system: 'SystemResponse' = None, + metadata: 'MessageContextMetadata' = None, + **kwargs) -> None: """ Initialize a Context object. @@ -3093,7 +3194,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -3110,7 +3211,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Context 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, @@ -3127,7 +3233,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'conversation_id', 'system', 'metadata'} if not hasattr(self, '_additionalProperties'): super(Context, self).__setattr__('_additionalProperties', set()) @@ -3135,17 +3245,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(Context, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this Context object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Context') -> 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): + def __ne__(self, other: 'Context') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3163,7 +3273,11 @@ class Counterexample(): the object. """ - def __init__(self, text, *, created=None, updated=None): + def __init__(self, + text: str, + *, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Counterexample object. @@ -3181,7 +3295,7 @@ def __init__(self, text, *, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} valid_keys = ['text', 'created', 'updated'] @@ -3201,7 +3315,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Counterexample 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: @@ -3212,17 +3331,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Counterexample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Counterexample') -> 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): + def __ne__(self, other: 'Counterexample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3231,16 +3354,17 @@ class CounterexampleCollection(): """ CounterexampleCollection. - :attr list[Counterexample] counterexamples: An array of objects describing the + :attr List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, counterexamples, pagination): + def __init__(self, counterexamples: List['Counterexample'], + pagination: 'Pagination') -> None: """ Initialize a CounterexampleCollection object. - :param list[Counterexample] counterexamples: An array of objects describing + :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. """ @@ -3248,7 +3372,7 @@ def __init__(self, counterexamples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} valid_keys = ['counterexamples', 'pagination'] @@ -3274,7 +3398,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CounterexampleCollection 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, @@ -3286,17 +3415,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 CounterexampleCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CounterexampleCollection') -> 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): + def __ne__(self, other: 'CounterexampleCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3318,19 +3451,19 @@ class CreateEntity(): :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to the object. - :attr list[CreateValue] values: (optional) An array of objects describing the + :attr List[CreateValue] values: (optional) An array of objects describing the entity values. """ def __init__(self, - entity, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - created=None, - updated=None, - values=None): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + created: datetime = None, + updated: datetime = None, + values: List['CreateValue'] = None) -> None: """ Initialize a CreateEntity object. @@ -3350,7 +3483,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[CreateValue] values: (optional) An array of objects describing + :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ self.entity = entity @@ -3362,7 +3495,7 @@ def __init__(self, self.values = values @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -3395,7 +3528,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEntity 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, 'entity') and self.entity is not None: @@ -3414,17 +3552,21 @@ def _to_dict(self): _dict['values'] = [x._to_dict() for x in self.values] return _dict - def __str__(self): + 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 CreateEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateEntity') -> 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): + def __ne__(self, other: 'CreateEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3443,17 +3585,17 @@ class CreateIntent(): :attr datetime created: (optional) The timestamp for creation of the object. :attr 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 + :attr List[Example] examples: (optional) An array of user input examples for the intent. """ def __init__(self, - intent, + intent: str, *, - description=None, - created=None, - updated=None, - examples=None): + description: str = None, + created: datetime = None, + updated: datetime = None, + examples: List['Example'] = None) -> None: """ Initialize a CreateIntent object. @@ -3468,7 +3610,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. """ self.intent = intent @@ -3478,7 +3620,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] @@ -3504,7 +3646,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateIntent 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, 'intent') and self.intent is not None: @@ -3519,17 +3666,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 CreateIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateIntent') -> 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): + def __ne__(self, other: 'CreateIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3544,12 +3695,12 @@ class CreateValue(): - 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. + :attr 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. + :attr 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 @@ -3560,14 +3711,14 @@ class CreateValue(): """ def __init__(self, - value, + value: str, *, - metadata=None, - type=None, - synonyms=None, - patterns=None, - created=None, - updated=None): + metadata: dict = None, + type: str = None, + synonyms: List[str] = None, + patterns: List[str] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a CreateValue object. @@ -3577,13 +3728,13 @@ def __init__(self, - It cannot consist of only whitespace characters. :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 + :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. - :param list[str] patterns: (optional) An array of patterns for the entity + :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 @@ -3602,7 +3753,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} valid_keys = [ @@ -3633,7 +3784,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateValue 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, 'value') and self.value is not None: @@ -3652,17 +3808,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 CreateValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateValue') -> 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): + def __ne__(self, other: 'CreateValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3705,7 +3865,7 @@ class DialogNode(): :attr str event_name: (optional) How an `event_handler` node is processed. :attr str variable: (optional) The location in the dialog context where output is stored. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :attr 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 digressed into. @@ -3724,29 +3884,29 @@ class DialogNode(): """ def __init__(self, - dialog_node, + dialog_node: str, *, - description=None, - conditions=None, - parent=None, - previous_sibling=None, - output=None, - context=None, - metadata=None, - next_step=None, - title=None, - type=None, - event_name=None, - variable=None, - actions=None, - digress_in=None, - digress_out=None, - digress_out_slots=None, - user_label=None, - disambiguation_opt_out=None, - disabled=None, - created=None, - updated=None): + description: str = None, + conditions: str = None, + parent: str = None, + previous_sibling: str = None, + output: 'DialogNodeOutput' = None, + context: dict = 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: """ Initialize a DialogNode object. @@ -3779,7 +3939,7 @@ def __init__(self, :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. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -3821,7 +3981,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} valid_keys = [ @@ -3889,7 +4049,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNode 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, 'dialog_node') and self.dialog_node is not None: @@ -3941,17 +4106,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 DialogNode object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNode') -> 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): + def __ne__(self, other: 'DialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4020,12 +4189,12 @@ class DialogNodeAction(): """ def __init__(self, - name, - result_variable, + name: str, + result_variable: str, *, - type=None, - parameters=None, - credentials=None): + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ Initialize a DialogNodeAction object. @@ -4045,7 +4214,7 @@ def __init__(self, self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} valid_keys = [ @@ -4076,7 +4245,12 @@ def _from_dict(cls, _dict): args['credentials'] = _dict.get('credentials') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeAction 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: @@ -4092,17 +4266,21 @@ def _to_dict(self): _dict['credentials'] = self.credentials return _dict - def __str__(self): + 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 DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeAction') -> 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): + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4121,16 +4299,17 @@ class DialogNodeCollection(): """ An array of dialog nodes. - :attr list[DialogNode] dialog_nodes: An array of objects describing the dialog + :attr 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. """ - def __init__(self, dialog_nodes, pagination): + def __init__(self, dialog_nodes: List['DialogNode'], + pagination: 'Pagination') -> None: """ Initialize a DialogNodeCollection object. - :param list[DialogNode] dialog_nodes: An array of objects describing the + :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ @@ -4138,7 +4317,7 @@ def __init__(self, dialog_nodes, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} valid_keys = ['dialog_nodes', 'pagination'] @@ -4163,7 +4342,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeCollection 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, 'dialog_nodes') and self.dialog_nodes is not None: @@ -4172,17 +4356,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 DialogNodeCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeCollection') -> 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): + def __ne__(self, other: 'DialogNodeCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4217,7 +4405,11 @@ class DialogNodeNextStep(): :attr str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, behavior, *, dialog_node=None, selector=None): + def __init__(self, + behavior: str, + *, + dialog_node: str = None, + selector: str = None) -> None: """ Initialize a DialogNodeNextStep object. @@ -4252,7 +4444,7 @@ def __init__(self, behavior, *, dialog_node=None, selector=None): self.selector = selector @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} valid_keys = ['behavior', 'dialog_node', 'selector'] @@ -4273,7 +4465,12 @@ def _from_dict(cls, _dict): args['selector'] = _dict.get('selector') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeNextStep 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, 'behavior') and self.behavior is not None: @@ -4284,17 +4481,21 @@ def _to_dict(self): _dict['selector'] = self.selector return _dict - def __str__(self): + 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 DialogNodeNextStep object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeNextStep') -> 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): + def __ne__(self, other: 'DialogNodeNextStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4345,17 +4546,21 @@ class DialogNodeOutput(): output, see the [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr list[DialogNodeOutputGeneric] generic: (optional) An array of objects + :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ - def __init__(self, *, generic=None, modifiers=None, **kwargs): + def __init__(self, + *, + generic: List['DialogNodeOutputGeneric'] = None, + modifiers: 'DialogNodeOutputModifiers' = None, + **kwargs) -> None: """ Initialize a DialogNodeOutput object. - :param list[DialogNodeOutputGeneric] generic: (optional) An array of + :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. @@ -4367,7 +4572,7 @@ def __init__(self, *, generic=None, modifiers=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -4384,7 +4589,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutput 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: @@ -4398,7 +4608,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'generic', 'modifiers'} if not hasattr(self, '_additionalProperties'): super(DialogNodeOutput, self).__setattr__('_additionalProperties', @@ -4407,17 +4621,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(DialogNodeOutput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutput') -> 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): + def __ne__(self, other: 'DialogNodeOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4430,7 +4644,7 @@ class DialogNodeOutputGeneric(): specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only by the v2 runtime API. - :attr list[DialogNodeOutputTextValuesElement] values: (optional) A list of one + :attr List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :attr str selection_policy: (optional) How a response is selected from the list, if more than one response is specified. Valid only when @@ -4450,7 +4664,7 @@ class DialogNodeOutputGeneric(): response. Valid only when **response_type**=`image` or `option`. :attr str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :attr str message_to_human_agent: (optional) An optional message to be sent to @@ -4473,23 +4687,23 @@ class DialogNodeOutputGeneric(): """ def __init__(self, - response_type, + response_type: str, *, - values=None, - selection_policy=None, - delimiter=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - query=None, - query_type=None, - filter=None, - discovery_version=None): + values: List['DialogNodeOutputTextValuesElement'] = None, + selection_policy: str = None, + delimiter: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + query: str = None, + query_type: str = None, + filter: str = None, + discovery_version: str = None) -> None: """ Initialize a DialogNodeOutputGeneric object. @@ -4498,7 +4712,7 @@ def __init__(self, channel. **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only by the v2 runtime API. - :param list[DialogNodeOutputTextValuesElement] values: (optional) A list of + :param List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :param str selection_policy: (optional) How a response is selected from the @@ -4519,7 +4733,7 @@ def __init__(self, response. Valid only when **response_type**=`image` or `option`. :param str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :param str message_to_human_agent: (optional) An optional message to be @@ -4558,7 +4772,7 @@ def __init__(self, self.discovery_version = discovery_version @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -4616,7 +4830,12 @@ def _from_dict(cls, _dict): args['discovery_version'] = _dict.get('discovery_version') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGeneric 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, 'response_type') and self.response_type is not None: @@ -4656,17 +4875,21 @@ def _to_dict(self): _dict['discovery_version'] = self.discovery_version return _dict - def __str__(self): + 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 DialogNodeOutputGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputGeneric') -> 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): + def __ne__(self, other: 'DialogNodeOutputGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4719,7 +4942,7 @@ class DialogNodeOutputModifiers(): values. """ - def __init__(self, *, overwrite=None): + def __init__(self, *, overwrite: bool = None) -> None: """ Initialize a DialogNodeOutputModifiers object. @@ -4731,7 +4954,7 @@ def __init__(self, *, overwrite=None): self.overwrite = overwrite @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} valid_keys = ['overwrite'] @@ -4744,24 +4967,33 @@ def _from_dict(cls, _dict): args['overwrite'] = _dict.get('overwrite') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputModifiers 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, 'overwrite') and self.overwrite is not None: _dict['overwrite'] = self.overwrite return _dict - def __str__(self): + 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 DialogNodeOutputModifiers object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputModifiers') -> 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): + def __ne__(self, other: 'DialogNodeOutputModifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4776,7 +5008,8 @@ class DialogNodeOutputOptionsElement(): corresponding option. """ - def __init__(self, label, value): + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -4789,7 +5022,7 @@ def __init__(self, label, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} valid_keys = ['label', 'value'] @@ -4813,7 +5046,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElement 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, 'label') and self.label is not None: @@ -4822,17 +5060,21 @@ def _to_dict(self): _dict['value'] = self.value._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4844,27 +5086,31 @@ class DialogNodeOutputOptionsElementValue(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be used + :attr 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 + :attr 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=None, intents=None, entities=None): + def __init__(self, + *, + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be + :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. - :param list[RuntimeEntity] entities: (optional) An array of entities to be + :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. @@ -4874,7 +5120,7 @@ def __init__(self, *, input=None, intents=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} valid_keys = ['input', 'intents', 'entities'] @@ -4895,7 +5141,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElementValue 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: @@ -4906,17 +5157,21 @@ def _to_dict(self): _dict['entities'] = [x._to_dict() for x in self.entities] return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4930,7 +5185,7 @@ class DialogNodeOutputTextValuesElement(): supported by the channel. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a DialogNodeOutputTextValuesElement object. @@ -4941,7 +5196,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -4954,24 +5209,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputTextValuesElement 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 __str__(self): + 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 DialogNodeOutputTextValuesElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputTextValuesElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4986,7 +5250,11 @@ class DialogNodeVisitedDetails(): :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, *, dialog_node=None, title=None, conditions=None): + def __init__(self, + *, + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ Initialize a DialogNodeVisitedDetails object. @@ -5001,7 +5269,7 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): self.conditions = conditions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} valid_keys = ['dialog_node', 'title', 'conditions'] @@ -5018,7 +5286,12 @@ def _from_dict(cls, _dict): args['conditions'] = _dict.get('conditions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeVisitedDetails 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, 'dialog_node') and self.dialog_node is not None: @@ -5029,17 +5302,21 @@ def _to_dict(self): _dict['conditions'] = self.conditions return _dict - def __str__(self): + 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 DialogNodeVisitedDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeVisitedDetails') -> 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): + def __ne__(self, other: 'DialogNodeVisitedDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5062,7 +5339,12 @@ class DialogSuggestion(): the dialog node's **user_label** property. """ - def __init__(self, label, value, *, output=None, dialog_node=None): + def __init__(self, + label: str, + value: 'DialogSuggestionValue', + *, + output: 'DialogSuggestionOutput' = None, + dialog_node: str = None) -> None: """ Initialize a DialogSuggestion object. @@ -5085,7 +5367,7 @@ def __init__(self, label, value, *, output=None, dialog_node=None): self.dialog_node = dialog_node @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} valid_keys = ['label', 'value', 'output', 'dialog_node'] @@ -5113,9 +5395,14 @@ def _from_dict(cls, _dict): args['dialog_node'] = _dict.get('dialog_node') return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestion 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, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: @@ -5126,17 +5413,21 @@ def _to_dict(self): _dict['dialog_node'] = self.dialog_node return _dict - def __str__(self): + 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 DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestion') -> 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): + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5146,40 +5437,40 @@ class DialogSuggestionOutput(): The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr list[str] nodes_visited: (optional) An array of the nodes that were + :attr 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 + :attr 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[str] text: An array of responses to the user. - :attr list[DialogSuggestionResponseGeneric] generic: (optional) Output intended + :attr List[str] text: An array of responses to the user. + :attr List[DialogSuggestionResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ def __init__(self, - text, + text: List[str], *, - nodes_visited=None, - nodes_visited_details=None, - generic=None, - **kwargs): + nodes_visited: List[str] = None, + nodes_visited_details: List['DialogNodeVisitedDetails'] = None, + generic: List['DialogSuggestionResponseGeneric'] = None, + **kwargs) -> None: """ Initialize a DialogSuggestionOutput object. - :param list[str] text: An array of responses to the user. - :param list[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] text: An array of responses to the user. + :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. - :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + :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. - :param list[DialogSuggestionResponseGeneric] generic: (optional) Output + :param List[DialogSuggestionResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :param **kwargs: (optional) Any additional properties. @@ -5192,7 +5483,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionOutput': """Initialize a DialogSuggestionOutput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -5221,7 +5512,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionOutput 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: @@ -5242,7 +5538,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'nodes_visited', 'nodes_visited_details', 'text', 'generic' } @@ -5253,17 +5553,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(DialogSuggestionOutput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this DialogSuggestionOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionOutput') -> 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): + def __ne__(self, other: 'DialogSuggestionOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5287,7 +5587,7 @@ class DialogSuggestionResponseGeneric(): 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: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -5299,19 +5599,19 @@ class DialogSuggestionResponseGeneric(): """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - dialog_node=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + dialog_node: str = None) -> None: """ Initialize a DialogSuggestionResponseGeneric object. @@ -5332,7 +5632,7 @@ def __init__(self, :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: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -5357,7 +5657,7 @@ def __init__(self, self.dialog_node = dialog_node @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionResponseGeneric': """Initialize a DialogSuggestionResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -5403,7 +5703,12 @@ def _from_dict(cls, _dict): args['dialog_node'] = _dict.get('dialog_node') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -5433,17 +5738,21 @@ def _to_dict(self): _dict['dialog_node'] = self.dialog_node return _dict - def __str__(self): + 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 DialogSuggestionResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionResponseGeneric') -> 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): + def __ne__(self, other: 'DialogSuggestionResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5478,21 +5787,25 @@ class DialogSuggestionValue(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be sent + :attr 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 + :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ - def __init__(self, *, input=None, intents=None, entities=None): + def __init__(self, + *, + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None) -> None: """ Initialize a DialogSuggestionValue object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be + :param List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :param list[RuntimeEntity] entities: (optional) An array of entities to be + :param List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ self.input = input @@ -5500,7 +5813,7 @@ def __init__(self, *, input=None, intents=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} valid_keys = ['input', 'intents', 'entities'] @@ -5521,7 +5834,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionValue 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: @@ -5532,17 +5850,21 @@ def _to_dict(self): _dict['entities'] = [x._to_dict() for x in self.entities] return _dict - def __str__(self): + 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 DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionValue') -> 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): + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5564,19 +5886,19 @@ class Entity(): :attr datetime created: (optional) The timestamp for creation of the object. :attr 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 + :attr List[Value] values: (optional) An array of objects describing the entity values. """ def __init__(self, - entity, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - created=None, - updated=None, - values=None): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + created: datetime = None, + updated: datetime = None, + values: List['Value'] = None) -> None: """ Initialize a Entity object. @@ -5596,7 +5918,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Value] values: (optional) An array of objects describing the + :param List[Value] values: (optional) An array of objects describing the entity values. """ self.entity = entity @@ -5608,7 +5930,7 @@ def __init__(self, self.values = values @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} valid_keys = [ @@ -5641,7 +5963,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Entity 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, 'entity') and self.entity is not None: @@ -5660,17 +5987,21 @@ def _to_dict(self): _dict['values'] = [x._to_dict() for x in self.values] return _dict - def __str__(self): + 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 Entity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Entity') -> 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): + def __ne__(self, other: 'Entity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5679,16 +6010,17 @@ class EntityCollection(): """ An array of objects describing the entities for the workspace. - :attr list[Entity] entities: An array of objects describing the entities defined + :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. """ - def __init__(self, entities, pagination): + def __init__(self, entities: List['Entity'], + pagination: 'Pagination') -> None: """ Initialize a EntityCollection object. - :param list[Entity] entities: An array of objects describing the entities + :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. """ @@ -5696,7 +6028,7 @@ def __init__(self, entities, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} valid_keys = ['entities', 'pagination'] @@ -5721,7 +6053,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityCollection 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, 'entities') and self.entities is not None: @@ -5730,17 +6067,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 EntityCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityCollection') -> 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): + def __ne__(self, other: 'EntityCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5751,17 +6092,17 @@ class EntityMention(): :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 + :attr 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, intent, location): + def __init__(self, text: str, intent: str, location: List[int]) -> None: """ Initialize a EntityMention object. :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 + :param List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.text = text @@ -5769,7 +6110,7 @@ def __init__(self, text, intent, location): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} valid_keys = ['text', 'intent', 'location'] @@ -5797,7 +6138,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMention 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: @@ -5808,17 +6154,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 EntityMention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMention') -> 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): + def __ne__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5827,16 +6177,17 @@ class EntityMentionCollection(): """ EntityMentionCollection. - :attr list[EntityMention] examples: An array of objects describing the entity + :attr 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. """ - def __init__(self, examples, pagination): + def __init__(self, examples: List['EntityMention'], + pagination: 'Pagination') -> None: """ Initialize a EntityMentionCollection object. - :param list[EntityMention] examples: An array of objects describing the + :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. """ @@ -5844,7 +6195,7 @@ def __init__(self, examples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} valid_keys = ['examples', 'pagination'] @@ -5869,7 +6220,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMentionCollection 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, 'examples') and self.examples is not None: @@ -5878,17 +6234,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 EntityMentionCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMentionCollection') -> 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): + def __ne__(self, other: 'EntityMentionCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5901,13 +6261,18 @@ class Example(): 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 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 the object. """ - def __init__(self, text, *, mentions=None, created=None, updated=None): + def __init__(self, + text: str, + *, + mentions: List['Mention'] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Example object. @@ -5915,7 +6280,7 @@ def __init__(self, text, *, mentions=None, created=None, updated=None): to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] mentions: (optional) An array of contextual entity + :param List[Mention] mentions: (optional) An array of contextual entity mentions. :param datetime created: (optional) The timestamp for creation of the object. @@ -5928,7 +6293,7 @@ def __init__(self, text, *, mentions=None, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} valid_keys = ['text', 'mentions', 'created', 'updated'] @@ -5952,7 +6317,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Example 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: @@ -5965,17 +6335,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Example object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Example') -> 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): + def __ne__(self, other: 'Example') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5984,16 +6358,17 @@ class ExampleCollection(): """ ExampleCollection. - :attr list[Example] examples: An array of objects describing the examples + :attr List[Example] examples: An array of objects describing the examples defined for the intent. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, examples, pagination): + def __init__(self, examples: List['Example'], + pagination: 'Pagination') -> None: """ Initialize a ExampleCollection object. - :param 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. :param Pagination pagination: The pagination data for the returned objects. """ @@ -6001,7 +6376,7 @@ def __init__(self, examples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} valid_keys = ['examples', 'pagination'] @@ -6026,7 +6401,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ExampleCollection 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, 'examples') and self.examples is not None: @@ -6035,17 +6415,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 ExampleCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ExampleCollection') -> 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): + def __ne__(self, other: 'ExampleCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6064,17 +6448,17 @@ class Intent(): :attr datetime created: (optional) The timestamp for creation of the object. :attr 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 + :attr List[Example] examples: (optional) An array of user input examples for the intent. """ def __init__(self, - intent, + intent: str, *, - description=None, - created=None, - updated=None, - examples=None): + description: str = None, + created: datetime = None, + updated: datetime = None, + examples: List['Example'] = None) -> None: """ Initialize a Intent object. @@ -6089,7 +6473,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. """ self.intent = intent @@ -6099,7 +6483,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] @@ -6125,7 +6509,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Intent 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, 'intent') and self.intent is not None: @@ -6140,17 +6529,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 Intent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Intent') -> 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): + def __ne__(self, other: 'Intent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6159,16 +6552,17 @@ class IntentCollection(): """ IntentCollection. - :attr list[Intent] intents: An array of objects describing the intents defined + :attr List[Intent] intents: An array of objects describing the intents defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, intents, pagination): + def __init__(self, intents: List['Intent'], + pagination: 'Pagination') -> None: """ Initialize a IntentCollection object. - :param list[Intent] intents: An array of objects describing the intents + :param List[Intent] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ @@ -6176,7 +6570,7 @@ def __init__(self, intents, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} valid_keys = ['intents', 'pagination'] @@ -6201,7 +6595,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IntentCollection 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, 'intents') and self.intents is not None: @@ -6210,17 +6609,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 IntentCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IntentCollection') -> 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): + def __ne__(self, other: 'IntentCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6243,8 +6646,9 @@ class Log(): made. """ - def __init__(self, request, response, log_id, request_timestamp, - response_timestamp, workspace_id, language): + 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. @@ -6270,7 +6674,7 @@ def __init__(self, request, response, log_id, request_timestamp, self.language = language @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} valid_keys = [ @@ -6321,7 +6725,12 @@ def _from_dict(cls, _dict): 'Required property \'language\' not present in Log JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log 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, 'request') and self.request is not None: @@ -6343,17 +6752,21 @@ def _to_dict(self): _dict['language'] = self.language return _dict - def __str__(self): + 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 Log object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Log') -> 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): + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6362,15 +6775,15 @@ class LogCollection(): """ LogCollection. - :attr list[Log] logs: An array of objects describing log events. + :attr List[Log] logs: An array of objects describing log events. :attr LogPagination pagination: The pagination data for the returned objects. """ - def __init__(self, logs, pagination): + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: """ Initialize a LogCollection object. - :param list[Log] logs: An array of objects describing log events. + :param List[Log] logs: An array of objects describing log events. :param LogPagination pagination: The pagination data for the returned objects. """ @@ -6378,7 +6791,7 @@ def __init__(self, logs, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} valid_keys = ['logs', 'pagination'] @@ -6401,7 +6814,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogCollection 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, 'logs') and self.logs is not None: @@ -6410,17 +6828,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 LogCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogCollection') -> 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): + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6433,7 +6855,7 @@ class LogMessage(): :attr str msg: The text of the log message. """ - def __init__(self, level, msg): + def __init__(self, level: str, msg: str) -> None: """ Initialize a LogMessage object. @@ -6444,7 +6866,7 @@ def __init__(self, level, msg): self.msg = msg @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} valid_keys = ['level', 'msg'] @@ -6465,7 +6887,12 @@ def _from_dict(cls, _dict): 'Required property \'msg\' not present in LogMessage JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessage 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, 'level') and self.level is not None: @@ -6474,17 +6901,21 @@ def _to_dict(self): _dict['msg'] = self.msg return _dict - def __str__(self): + 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 LogMessage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogMessage') -> 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): + def __ne__(self, other: 'LogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6507,7 +6938,11 @@ class LogPagination(): :attr str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, *, next_url=None, matched=None, next_cursor=None): + def __init__(self, + *, + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: """ Initialize a LogPagination object. @@ -6522,7 +6957,7 @@ def __init__(self, *, next_url=None, matched=None, next_cursor=None): self.next_cursor = next_cursor @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} valid_keys = ['next_url', 'matched', 'next_cursor'] @@ -6539,7 +6974,12 @@ def _from_dict(cls, _dict): args['next_cursor'] = _dict.get('next_cursor') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogPagination 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, 'next_url') and self.next_url is not None: @@ -6550,17 +6990,21 @@ def _to_dict(self): _dict['next_cursor'] = self.next_cursor return _dict - def __str__(self): + 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 LogPagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogPagination') -> 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): + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6570,23 +7014,23 @@ 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 + :attr 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, location): + def __init__(self, entity: str, location: List[int]) -> None: """ Initialize a Mention object. :param str entity: The name of the entity. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.entity = entity self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} valid_keys = ['entity', 'location'] @@ -6607,7 +7051,12 @@ def _from_dict(cls, _dict): 'Required property \'location\' not present in Mention JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Mention 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, 'entity') and self.entity is not None: @@ -6616,17 +7065,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 Mention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Mention') -> 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): + def __ne__(self, other: 'Mention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6645,7 +7098,7 @@ class MessageContextMetadata(): string cannot contain carriage return, newline, or tab characters. """ - def __init__(self, *, deployment=None, user_id=None): + def __init__(self, *, deployment: str = None, user_id: str = None) -> None: """ Initialize a MessageContextMetadata object. @@ -6663,7 +7116,7 @@ def __init__(self, *, deployment=None, user_id=None): self.user_id = user_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} valid_keys = ['deployment', 'user_id'] @@ -6678,7 +7131,12 @@ def _from_dict(cls, _dict): args['user_id'] = _dict.get('user_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextMetadata 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, 'deployment') and self.deployment is not None: @@ -6687,17 +7145,21 @@ def _to_dict(self): _dict['user_id'] = self.user_id return _dict - def __str__(self): + 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 MessageContextMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextMetadata') -> 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): + def __ne__(self, other: 'MessageContextMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6710,7 +7172,7 @@ class MessageInput(): contain carriage return, newline, or tab characters. """ - def __init__(self, *, text=None, **kwargs): + def __init__(self, *, text: str = None, **kwargs) -> None: """ Initialize a MessageInput object. @@ -6723,7 +7185,7 @@ def __init__(self, *, text=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -6733,7 +7195,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput 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: @@ -6745,7 +7212,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'text'} if not hasattr(self, '_additionalProperties'): super(MessageInput, self).__setattr__('_additionalProperties', @@ -6754,17 +7225,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(MessageInput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInput') -> 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): + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6775,10 +7246,10 @@ class MessageRequest(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + :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 + :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 bool alternate_intents: (optional) Whether to return more than one intent. @@ -6787,29 +7258,29 @@ class MessageRequest(): maintain state, include the context from the previous response. :attr 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 + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ def __init__(self, *, - input=None, - intents=None, - entities=None, - alternate_intents=None, - context=None, - output=None, - actions=None): + 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) -> None: """ Initialize a MessageRequest object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :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 + :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. @@ -6820,7 +7291,7 @@ def __init__(self, :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. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ self.input = input @@ -6832,7 +7303,7 @@ def __init__(self, self.actions = actions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} valid_keys = [ @@ -6866,7 +7337,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @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: @@ -6886,17 +7362,21 @@ def _to_dict(self): _dict['actions'] = [x._to_dict() for x in self.actions] return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6907,9 +7387,9 @@ class MessageResponse(): 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 + :attr 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 + :attr 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. @@ -6917,26 +7397,26 @@ class MessageResponse(): state, include the context from the previous response. :attr 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 + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ def __init__(self, - input, - intents, - entities, - context, - output, + input: 'MessageInput', + intents: List['RuntimeIntent'], + entities: List['RuntimeEntity'], + context: 'Context', + output: 'OutputData', *, - alternate_intents=None, - actions=None): + alternate_intents: bool = None, + actions: List['DialogNodeAction'] = None) -> None: """ Initialize a MessageResponse object. :param MessageInput input: An input object that includes the input text. - :param list[RuntimeIntent] intents: An array of intents recognized in the + :param List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :param list[RuntimeEntity] entities: An array of entities identified in the + :param List[RuntimeEntity] entities: An array of entities identified in the user input. :param Context context: State information for the conversation. To maintain state, include the context from the previous response. @@ -6944,7 +7424,7 @@ def __init__(self, the user, the dialog nodes that were triggered, and messages from the log. :param bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ self.input = input @@ -6956,7 +7436,7 @@ def __init__(self, self.actions = actions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -7010,7 +7490,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @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, 'input') and self.input is not None: @@ -7030,17 +7515,21 @@ def _to_dict(self): _dict['actions'] = [x._to_dict() for x in self.actions] return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7050,45 +7539,45 @@ 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 + :attr 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 + :attr 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 + :attr List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr list[str] text: An array of responses to the user. - :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + :attr List[str] text: An array of responses to the user. + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ def __init__(self, - log_messages, - text, + log_messages: List['LogMessage'], + text: List[str], *, - nodes_visited=None, - nodes_visited_details=None, - generic=None, - **kwargs): + nodes_visited: List[str] = None, + nodes_visited_details: List['DialogNodeVisitedDetails'] = None, + generic: List['RuntimeResponseGeneric'] = None, + **kwargs) -> None: """ Initialize a OutputData object. - :param list[LogMessage] log_messages: An array of up to 50 messages logged + :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :param list[str] text: An array of responses to the user. - :param list[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] text: An array of responses to the user. + :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. - :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + :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. - :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + :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 **kwargs: (optional) Any additional properties. @@ -7102,7 +7591,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -7139,7 +7628,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OutputData 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: @@ -7162,7 +7656,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', 'generic' @@ -7173,17 +7671,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(OutputData, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this OutputData object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OutputData') -> 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): + def __ne__(self, other: 'OutputData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7203,13 +7701,13 @@ class Pagination(): """ def __init__(self, - refresh_url, + refresh_url: str, *, - next_url=None, - total=None, - matched=None, - refresh_cursor=None, - next_cursor=None): + next_url: str = None, + total: int = None, + matched: int = None, + refresh_cursor: str = None, + next_cursor: str = None) -> None: """ Initialize a Pagination object. @@ -7231,7 +7729,7 @@ def __init__(self, self.next_cursor = next_cursor @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} valid_keys = [ @@ -7261,7 +7759,12 @@ def _from_dict(cls, _dict): args['next_cursor'] = _dict.get('next_cursor') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_url') and self.refresh_url is not None: @@ -7278,17 +7781,21 @@ def _to_dict(self): _dict['next_cursor'] = self.next_cursor return _dict - def __str__(self): + 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 Pagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pagination') -> 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): + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7298,35 +7805,35 @@ 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: An array of zero-based character offsets that indicate + :attr List[int] location: 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 confidence in the recognized entity. :attr dict metadata: (optional) Any metadata for the entity. - :attr list[CaptureGroup] groups: (optional) The recognized capture groups for + :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, - entity, - location, - value, + entity: str, + location: List[int], + value: str, *, - confidence=None, - metadata=None, - groups=None): + confidence: float = None, + metadata: dict = None, + groups: List['CaptureGroup'] = None) -> None: """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: 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. :param dict metadata: (optional) Any metadata for the entity. - :param list[CaptureGroup] groups: (optional) The recognized capture groups + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ self.entity = entity @@ -7337,7 +7844,7 @@ def __init__(self, self.groups = groups @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -7375,7 +7882,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: @@ -7392,17 +7904,21 @@ def _to_dict(self): _dict['groups'] = [x._to_dict() for x in self.groups] return _dict - def __str__(self): + 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 RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeEntity') -> 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): + def __ne__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7416,7 +7932,7 @@ class RuntimeIntent(): in the intent. """ - def __init__(self, intent, confidence): + def __init__(self, intent: str, confidence: float) -> None: """ Initialize a RuntimeIntent object. @@ -7428,7 +7944,7 @@ def __init__(self, intent, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'confidence'] @@ -7451,7 +7967,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: @@ -7460,17 +7981,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeIntent') -> 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): + def __ne__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7492,7 +8017,7 @@ class RuntimeResponseGeneric(): 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: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -7501,27 +8026,27 @@ class RuntimeResponseGeneric(): :attr str dialog_node: (optional) The 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 **user_label** property. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects + :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Plus and Premium users. """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - dialog_node=None, - suggestions=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + dialog_node: str = None, + suggestions: List['DialogSuggestion'] = None) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -7540,7 +8065,7 @@ def __init__(self, :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: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -7550,7 +8075,7 @@ def __init__(self, :param str dialog_node: (optional) The 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 **user_label** property. - :param list[DialogSuggestion] suggestions: (optional) An array of objects + :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation @@ -7571,7 +8096,7 @@ def __init__(self, self.suggestions = suggestions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -7622,7 +8147,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -7654,17 +8184,21 @@ def _to_dict(self): _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict - def __str__(self): + 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 RuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeResponseGeneric') -> 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): + def __ne__(self, other: 'RuntimeResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7703,7 +8237,11 @@ class Synonym(): the object. """ - def __init__(self, synonym, *, created=None, updated=None): + def __init__(self, + synonym: str, + *, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Synonym object. @@ -7721,7 +8259,7 @@ def __init__(self, synonym, *, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} valid_keys = ['synonym', 'created', 'updated'] @@ -7741,7 +8279,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Synonym 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, 'synonym') and self.synonym is not None: @@ -7752,17 +8295,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Synonym object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Synonym') -> 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): + def __ne__(self, other: 'Synonym') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7771,22 +8318,23 @@ class SynonymCollection(): """ SynonymCollection. - :attr list[Synonym] synonyms: An array of synonyms. + :attr List[Synonym] synonyms: An array of synonyms. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, synonyms, pagination): + def __init__(self, synonyms: List['Synonym'], + pagination: 'Pagination') -> None: """ Initialize a SynonymCollection object. - :param list[Synonym] synonyms: An array of synonyms. + :param List[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. """ self.synonyms = synonyms self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} valid_keys = ['synonyms', 'pagination'] @@ -7811,7 +8359,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SynonymCollection 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, 'synonyms') and self.synonyms is not None: @@ -7820,17 +8373,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 SynonymCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SynonymCollection') -> 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): + def __ne__(self, other: 'SynonymCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7841,7 +8398,7 @@ class SystemResponse(): """ - def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """ Initialize a SystemResponse object. @@ -7851,14 +8408,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SystemResponse': """Initialize a SystemResponse object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SystemResponse 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, '_additionalProperties'): @@ -7868,7 +8430,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(SystemResponse, self).__setattr__('_additionalProperties', @@ -7877,17 +8443,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(SystemResponse, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this SystemResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SystemResponse') -> 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): + def __ne__(self, other: 'SystemResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7902,12 +8468,12 @@ class Value(): - 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. + :attr 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. + :attr 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 @@ -7918,14 +8484,14 @@ class Value(): """ def __init__(self, - value, - type, + value: str, + type: str, *, - metadata=None, - synonyms=None, - patterns=None, - created=None, - updated=None): + metadata: dict = None, + synonyms: List[str] = None, + patterns: List[str] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Value object. @@ -7935,13 +8501,13 @@ def __init__(self, - It cannot consist of only whitespace characters. :param str type: Specifies the type of entity value. :param dict metadata: (optional) Any metadata related to the entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity + :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. - :param list[str] patterns: (optional) An array of patterns for the entity + :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 @@ -7960,7 +8526,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} valid_keys = [ @@ -7994,7 +8560,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Value 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, 'value') and self.value is not None: @@ -8013,17 +8584,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Value object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Value') -> 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): + def __ne__(self, other: 'Value') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8039,22 +8614,22 @@ class ValueCollection(): """ ValueCollection. - :attr list[Value] values: An array of entity values. + :attr List[Value] values: An array of entity values. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, values, pagination): + def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: """ Initialize a ValueCollection object. - :param list[Value] values: An array of entity values. + :param List[Value] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. """ self.values = values self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} valid_keys = ['values', 'pagination'] @@ -8079,7 +8654,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ValueCollection 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, 'values') and self.values is not None: @@ -8088,17 +8668,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 ValueCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ValueCollection') -> 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): + def __ne__(self, other: 'ValueCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8113,11 +8697,15 @@ class Webhook(): to send HTTP POST requests. :attr 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 + :attr List[WebhookHeader] headers: (optional) An optional array of HTTP headers to pass with the HTTP request. """ - def __init__(self, url, name, *, headers=None): + def __init__(self, + url: str, + name: str, + *, + headers: List['WebhookHeader'] = None) -> None: """ Initialize a Webhook object. @@ -8125,7 +8713,7 @@ def __init__(self, url, name, *, headers=None): you want to send HTTP POST requests. :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :param list[WebhookHeader] headers: (optional) An optional array of HTTP + :param List[WebhookHeader] headers: (optional) An optional array of HTTP headers to pass with the HTTP request. """ self.url = url @@ -8133,7 +8721,7 @@ def __init__(self, url, name, *, headers=None): self.headers = headers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} valid_keys = ['url', 'name', 'headers'] @@ -8158,7 +8746,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Webhook 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, 'url') and self.url is not None: @@ -8169,17 +8762,21 @@ def _to_dict(self): _dict['headers'] = [x._to_dict() for x in self.headers] return _dict - def __str__(self): + 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 Webhook object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Webhook') -> 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): + def __ne__(self, other: 'Webhook') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8192,7 +8789,7 @@ class WebhookHeader(): :attr str value: The value of an HTTP header. """ - def __init__(self, name, value): + def __init__(self, name: str, value: str) -> None: """ Initialize a WebhookHeader object. @@ -8203,7 +8800,7 @@ def __init__(self, name, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} valid_keys = ['name', 'value'] @@ -8224,7 +8821,12 @@ def _from_dict(cls, _dict): 'Required property \'value\' not present in WebhookHeader JSON') return cls(**args) - def _to_dict(self): + @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: @@ -8233,17 +8835,21 @@ def _to_dict(self): _dict['value'] = self.value return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'WebhookHeader') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8268,33 +8874,33 @@ class Workspace(): :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to the object. - :attr list[Intent] intents: (optional) An array of intents. - :attr list[Entity] entities: (optional) An array of objects describing the + :attr List[Intent] intents: (optional) An array of intents. + :attr List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :attr list[DialogNode] dialog_nodes: (optional) An array of objects describing + :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :attr list[Counterexample] counterexamples: (optional) An array of + :attr List[Counterexample] counterexamples: (optional) An array of counterexamples. - :attr list[Webhook] webhooks: (optional) + :attr List[Webhook] webhooks: (optional) """ def __init__(self, - name, - language, - learning_opt_out, - workspace_id, + name: str, + language: str, + learning_opt_out: bool, + workspace_id: str, *, - description=None, - metadata=None, - system_settings=None, - status=None, - created=None, - updated=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None): + description: str = None, + metadata: dict = None, + system_settings: 'WorkspaceSystemSettings' = None, + status: str = None, + created: datetime = None, + updated: datetime = None, + intents: List['Intent'] = None, + entities: List['Entity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None) -> None: """ Initialize a Workspace object. @@ -8316,14 +8922,14 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Intent] intents: (optional) An array of intents. - :param list[Entity] entities: (optional) An array of objects describing the + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param list[Counterexample] counterexamples: (optional) An array of + :param List[Counterexample] counterexamples: (optional) An array of counterexamples. - :param list[Webhook] webhooks: (optional) + :param List[Webhook] webhooks: (optional) """ self.name = name self.description = description @@ -8342,7 +8948,7 @@ def __init__(self, self.webhooks = webhooks @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} valid_keys = [ @@ -8413,7 +9019,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Workspace 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: @@ -8453,17 +9064,21 @@ def _to_dict(self): _dict['webhooks'] = [x._to_dict() for x in self.webhooks] return _dict - def __str__(self): + 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 Workspace object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Workspace') -> 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): + def __ne__(self, other: 'Workspace') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8482,16 +9097,17 @@ class WorkspaceCollection(): """ WorkspaceCollection. - :attr list[Workspace] workspaces: An array of objects describing the workspaces + :attr 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. """ - def __init__(self, workspaces, pagination): + def __init__(self, workspaces: List['Workspace'], + pagination: 'Pagination') -> None: """ Initialize a WorkspaceCollection object. - :param list[Workspace] workspaces: An array of objects describing the + :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. """ @@ -8499,7 +9115,7 @@ def __init__(self, workspaces, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} valid_keys = ['workspaces', 'pagination'] @@ -8524,7 +9140,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCollection 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, 'workspaces') and self.workspaces is not None: @@ -8533,17 +9154,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 WorkspaceCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceCollection') -> 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): + def __ne__(self, other: 'WorkspaceCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8564,10 +9189,10 @@ class WorkspaceSystemSettings(): def __init__(self, *, - tooling=None, - disambiguation=None, - human_agent_assist=None, - off_topic=None): + tooling: 'WorkspaceSystemSettingsTooling' = None, + disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, + human_agent_assist: dict = None, + off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -8586,7 +9211,7 @@ def __init__(self, self.off_topic = off_topic @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} valid_keys = [ @@ -8611,7 +9236,12 @@ def _from_dict(cls, _dict): _dict.get('off_topic')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettings 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, 'tooling') and self.tooling is not None: @@ -8626,17 +9256,21 @@ def _to_dict(self): _dict['off_topic'] = self.off_topic._to_dict() return _dict - def __str__(self): + 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 WorkspaceSystemSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettings') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8667,13 +9301,13 @@ class WorkspaceSystemSettingsDisambiguation(): def __init__(self, *, - prompt=None, - none_of_the_above_prompt=None, - enabled=None, - sensitivity=None, - randomize=None, - max_suggestions=None, - suggestion_text_policy=None): + 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: """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -8704,7 +9338,7 @@ def __init__(self, self.suggestion_text_policy = suggestion_text_policy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} valid_keys = [ @@ -8733,7 +9367,12 @@ def _from_dict(cls, _dict): args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsDisambiguation 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, 'prompt') and self.prompt is not None: @@ -8755,17 +9394,21 @@ def _to_dict(self): _dict['suggestion_text_policy'] = self.suggestion_text_policy return _dict - def __str__(self): + 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 WorkspaceSystemSettingsDisambiguation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8787,7 +9430,7 @@ class WorkspaceSystemSettingsOffTopic(): for the workspace. """ - def __init__(self, *, enabled=None): + def __init__(self, *, enabled: bool = None) -> None: """ Initialize a WorkspaceSystemSettingsOffTopic object. @@ -8797,7 +9440,7 @@ def __init__(self, *, enabled=None): self.enabled = enabled @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} valid_keys = ['enabled'] @@ -8810,24 +9453,33 @@ def _from_dict(cls, _dict): args['enabled'] = _dict.get('enabled') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsOffTopic 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, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled return _dict - def __str__(self): + 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 WorkspaceSystemSettingsOffTopic object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsOffTopic') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8840,7 +9492,7 @@ class WorkspaceSystemSettingsTooling(): displays text responses within the `output.generic` object. """ - def __init__(self, *, store_generic_responses=None): + def __init__(self, *, store_generic_responses: bool = None) -> None: """ Initialize a WorkspaceSystemSettingsTooling object. @@ -8850,7 +9502,7 @@ def __init__(self, *, store_generic_responses=None): self.store_generic_responses = store_generic_responses @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} valid_keys = ['store_generic_responses'] @@ -8864,7 +9516,12 @@ def _from_dict(cls, _dict): 'store_generic_responses') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsTooling 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, 'store_generic_responses' @@ -8872,16 +9529,20 @@ def _to_dict(self): _dict['store_generic_responses'] = self.store_generic_responses return _dict - def __str__(self): + 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 WorkspaceSystemSettingsTooling object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsTooling') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 8ef258a87..458f26b46 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,1576 +1,3565 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import datetime -from dateutil.tz import tzutc +import pytest import responses -import ibm_watson -from ibm_watson import ApiException -from ibm_watson.assistant_v1 import Context, Counterexample, \ - CounterexampleCollection, Entity, EntityCollection, Example, \ - ExampleCollection, MessageInput, Intent, IntentCollection, Synonym, \ - SynonymCollection, Value, ValueCollection, Workspace, WorkspaceCollection, Webhook, WebhookHeader -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/assistant/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -######################### -# counterexamples -######################### - - -@responses.activate -def test_create_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "I want financial advice today.", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) - service.set_service_url(base_url) - counterexample = service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -@responses.activate -def test_rate_limit_exceeded(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - error_code = 429 - error_msg = 'Rate limit exceeded' - responses.add( - responses.POST, - url, - body='Rate limit exceeded', - status=429, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) +import ibm_watson.assistant_v1 +from ibm_watson.assistant_v1 import * + +base_url = 'https://gateway.watsonplatform.net/assistant/api' + +############################################################################## +# Start of Service: Message +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for message +#----------------------------------------------------------------------------- +class TestMessage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_response(self): + body = self.construct_full_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_empty(self): + check_empty_required_params(self, fake_response_MessageResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/message'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.message(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) + body['nodes_visited_details'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Message +############################################################################## + +############################################################################## +# Start of Service: Workspaces +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_workspaces +#----------------------------------------------------------------------------- +class TestListWorkspaces(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_workspaces_response(self): + body = self.construct_full_body() + response = fake_response_WorkspaceCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_workspaces_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_WorkspaceCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_workspaces_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_workspaces(**body) + return output + + def construct_full_body(self): + body = dict() + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_workspace +#----------------------------------------------------------------------------- +class TestCreateWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_workspace_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "system_settings": WorkspaceSystemSettings._from_dict(json.loads("""{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_workspace +#----------------------------------------------------------------------------- +class TestGetWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_workspace_empty(self): + check_empty_required_params(self, fake_response_Workspace_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['include_audit'] = True + body['sort'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_workspace +#----------------------------------------------------------------------------- +class TestUpdateWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_workspace_empty(self): + check_empty_required_params(self, fake_response_Workspace_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "system_settings": WorkspaceSystemSettings._from_dict(json.loads("""{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body['append'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_workspace +#----------------------------------------------------------------------------- +class TestDeleteWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_workspace_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_workspace_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Workspaces +############################################################################## + +############################################################################## +# Start of Service: Intents +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_intents +#----------------------------------------------------------------------------- +class TestListIntents(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_intents_response(self): + body = self.construct_full_body() + response = fake_response_IntentCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_intents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IntentCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_intents_empty(self): + check_empty_required_params(self, fake_response_IntentCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_intents(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_intent +#----------------------------------------------------------------------------- +class TestCreateIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"intent": "string1", "description": "string1", "examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"intent": "string1", "description": "string1", "examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_intent +#----------------------------------------------------------------------------- +class TestGetIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_intent +#----------------------------------------------------------------------------- +class TestUpdateIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_intent +#----------------------------------------------------------------------------- +class TestDeleteIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_intent_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_intent_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Intents +############################################################################## + +############################################################################## +# Start of Service: Examples +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_examples +#----------------------------------------------------------------------------- +class TestListExamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_examples_response(self): + body = self.construct_full_body() + response = fake_response_ExampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_examples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ExampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_examples_empty(self): + check_empty_required_params(self, fake_response_ExampleCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_examples(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_example +#----------------------------------------------------------------------------- +class TestCreateExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"text": "string1", "mentions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"text": "string1", "mentions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_example +#----------------------------------------------------------------------------- +class TestGetExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_example +#----------------------------------------------------------------------------- +class TestUpdateExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", "new_mentions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", "new_mentions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_example +#----------------------------------------------------------------------------- +class TestDeleteExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_example_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_example_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Examples +############################################################################## + +############################################################################## +# Start of Service: Counterexamples +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_counterexamples +#----------------------------------------------------------------------------- +class TestListCounterexamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_counterexamples_response(self): + body = self.construct_full_body() + response = fake_response_CounterexampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_counterexamples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CounterexampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_counterexamples_empty(self): + check_empty_required_params(self, fake_response_CounterexampleCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_counterexamples(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_counterexample +#----------------------------------------------------------------------------- +class TestCreateCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"text": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"text": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_counterexample +#----------------------------------------------------------------------------- +class TestGetCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_counterexample +#----------------------------------------------------------------------------- +class TestUpdateCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_counterexample +#----------------------------------------------------------------------------- +class TestDeleteCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_counterexample_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_counterexample_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Counterexamples +############################################################################## + +############################################################################## +# Start of Service: Entities +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_entities +#----------------------------------------------------------------------------- +class TestListEntities(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_entities_response(self): + body = self.construct_full_body() + response = fake_response_EntityCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_entities_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_EntityCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_entities_empty(self): + check_empty_required_params(self, fake_response_EntityCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_entities(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_entity +#----------------------------------------------------------------------------- +class TestCreateEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_entity +#----------------------------------------------------------------------------- +class TestGetEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_entity +#----------------------------------------------------------------------------- +class TestUpdateEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_entity +#----------------------------------------------------------------------------- +class TestDeleteEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_entity_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_entity_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Entities +############################################################################## + +############################################################################## +# Start of Service: Mentions +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_mentions +#----------------------------------------------------------------------------- +class TestListMentions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_mentions_response(self): + body = self.construct_full_body() + response = fake_response_EntityMentionCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_mentions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_EntityMentionCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_mentions_empty(self): + check_empty_required_params(self, fake_response_EntityMentionCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_mentions(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Mentions +############################################################################## + +############################################################################## +# Start of Service: Values +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_values +#----------------------------------------------------------------------------- +class TestListValues(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_values_response(self): + body = self.construct_full_body() + response = fake_response_ValueCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_values_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ValueCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_values_empty(self): + check_empty_required_params(self, fake_response_ValueCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_values(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_value +#----------------------------------------------------------------------------- +class TestCreateValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_value +#----------------------------------------------------------------------------- +class TestGetValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_value +#----------------------------------------------------------------------------- +class TestUpdateValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_value +#----------------------------------------------------------------------------- +class TestDeleteValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_value_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_value_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Values +############################################################################## + +############################################################################## +# Start of Service: Synonyms +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_synonyms +#----------------------------------------------------------------------------- +class TestListSynonyms(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_synonyms_response(self): + body = self.construct_full_body() + response = fake_response_SynonymCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_synonyms_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SynonymCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_synonyms_empty(self): + check_empty_required_params(self, fake_response_SynonymCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_synonyms(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_synonym +#----------------------------------------------------------------------------- +class TestCreateSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"synonym": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"synonym": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_synonym +#----------------------------------------------------------------------------- +class TestGetSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_synonym +#----------------------------------------------------------------------------- +class TestUpdateSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body.update({"new_synonym": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body.update({"new_synonym": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_synonym +#----------------------------------------------------------------------------- +class TestDeleteSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_synonym_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_synonym_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Synonyms +############################################################################## + +############################################################################## +# Start of Service: DialogNodes +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_dialog_nodes +#----------------------------------------------------------------------------- +class TestListDialogNodes(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_dialog_nodes_response(self): + body = self.construct_full_body() + response = fake_response_DialogNodeCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_dialog_nodes_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNodeCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_dialog_nodes_empty(self): + check_empty_required_params(self, fake_response_DialogNodeCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_dialog_nodes(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_dialog_node +#----------------------------------------------------------------------------- +class TestCreateDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_dialog_node +#----------------------------------------------------------------------------- +class TestGetDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_dialog_node +#----------------------------------------------------------------------------- +class TestUpdateDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_dialog_node +#----------------------------------------------------------------------------- +class TestDeleteDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_dialog_node_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: DialogNodes +############################################################################## + +############################################################################## +# Start of Service: Logs +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_logs +#----------------------------------------------------------------------------- +class TestListLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/logs'.format(body['workspace_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['sort'] = "string1" + body['filter'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_all_logs +#----------------------------------------------------------------------------- +class TestListAllLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_all_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_all_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_all_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/logs' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_all_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['filter'] = "string1" + body['sort'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['filter'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=202, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False try: - service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.') - except ApiException as ex: - assert len(responses.calls) == 1 - assert isinstance(ex, ApiException) - assert error_code == ex.code - assert error_msg in str(ex) - -@responses.activate -def test_unknown_error(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - error_msg = 'Unknown error' - responses.add( - responses.POST, - url, - status=407, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False try: - service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.') - except ApiException as ex: - assert len(responses.calls) == 1 - assert error_msg in str(ex) - -@responses.activate -def test_delete_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'I%20want%20financial%20advice%20today') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=response, - status=204, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.delete_counterexample( - workspace_id='boguswid', text='I want financial advice today').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample is None - - -@responses.activate -def test_get_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'What%20are%20you%20wearing%3F') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "What are you wearing?", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2016-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.get_counterexample( - workspace_id='boguswid', text='What are you wearing?').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -@responses.activate -def test_list_counterexamples(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "counterexamples": [{ - "text": "I want financial advice today.", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "text": "What are you wearing today", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/counterexamples?version=2017-12-18&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/counterexamples?cursor=base64=&version=2017-12-18&page_limit=2" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexamples = service.list_counterexamples(workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexamples == response - # Verify that response can be converted to a CounterexampleCollection - CounterexampleCollection._from_dict(counterexamples) - -@responses.activate -def test_update_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'What%20are%20you%20wearing%3F') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "What are you wearing?", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.update_counterexample( - workspace_id='boguswid', - text='What are you wearing?', - new_text='What are you wearing?').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -######################### -# entities -######################### - - -@responses.activate -def test_create_entity(): - endpoint = '/v1/workspaces/{0}/entities'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.create_entity( - workspace_id='boguswid', - entity='pizza_toppings', - description='Tasty pizza toppings', - metadata={"property": "value"}, - values=None, - fuzzy_match=None).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - -@responses.activate -def test_delete_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = "" - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.delete_entity(workspace_id='boguswid', entity='pizza_toppings').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == "" - - -@responses.activate -def test_get_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.get_entity(workspace_id='boguswid', entity='pizza_toppings', export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - - -@responses.activate -def test_list_entities(): - endpoint = '/v1/workspaces/{0}/entities'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entities": [{ - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities?version=2017-12-18&filter=name:pizza&include_count=true&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/entities?cursor=base64=&version=2017-12-18&filter=name:pizza&page_limit=1", - "total": - 1, - "matched": - 1 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entities = service.list_entities( - workspace_id='boguswid', - export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entities == response - # Verify that response can be converted to an EntityCollection - EntityCollection._from_dict(entities) - - -@responses.activate -def test_update_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.update_entity( - workspace_id='boguswid', - entity='pizza_toppings', - new_entity='pizza_toppings').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - - -######################### -# examples -######################### - - -@responses.activate -def test_create_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - 'boguswid', 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.create_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni', - mentions=[{'entity': 'xxx', 'location': [0, 1]}]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -@responses.activate -def test_delete_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.delete_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example is None - - -@responses.activate -def test_get_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2016-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) - example = service.get_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -@responses.activate -def test_list_examples(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - 'boguswid', 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "examples": [{ - "text": "Can I order a pizza?", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/intents/order/examples?version=2017-12-18&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/intents/order/examples?cursor=base64=&version=2017-12-18&page_limit=2" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - examples = service.list_examples( - workspace_id='boguswid', intent='pizza_order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert examples == response - # Verify that response can be converted to an ExampleCollection - ExampleCollection._from_dict(examples) - - -@responses.activate -def test_update_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.update_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni', - new_text='Gimme a pizza with pepperoni', - new_mentions=[{'entity': 'xxx', 'location': [0, 1]}]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -######################### -# intents -######################### - - -@responses.activate -def test_create_intent(): - endpoint = '/v1/workspaces/{0}/intents'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.create_intent( - workspace_id='boguswid', - intent='pizza_order', - description='User wants to start a new pizza order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - - -@responses.activate -def test_delete_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.delete_intent( - workspace_id='boguswid', intent='pizza_order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent is None - - -@responses.activate -def test_get_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.get_intent( - workspace_id='boguswid', intent='pizza_order', export=False).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - -@responses.activate -def test_list_intents(): - endpoint = '/v1/workspaces/{0}/intents'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intents": [{ - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/intents?version=2017-12-18&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/intents?cursor=base64=&version=2017-12-18&page_limit=1" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intents = service.list_intents(workspace_id='boguswid', export=False).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intents == response - # Verify that response can be converted to an IntentCollection - IntentCollection._from_dict(intents) - -@responses.activate -def test_update_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.update_intent( - workspace_id='boguswid', - intent='pizza_order', - new_intent='pizza_order', - new_description='User wants to start a new pizza order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - -def test_intent_models(): - intent = Intent(intent="pizza_order", - created=datetime.datetime(2015, 12, 6, 23, 53, 59, 15300, tzinfo=tzutc()), - updated=datetime.datetime(2015, 12, 7, 18, 53, 59, 15300, tzinfo=tzutc()), - description="User wants to start a new pizza order") - intentDict = intent._to_dict() - check = Intent._from_dict(intentDict) - assert intent == check - - -######################### -# logs -######################### - - -@responses.activate -def test_list_logs(): - endpoint = '/v1/workspaces/{0}/logs'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "logs": [{ - "request": { - "input": { - "text": "Can you turn off the AC" - }, - "context": { - "conversation_id": "f2c7e362-4cc8-4761-8b0f-9ccd70c63bca", - "system": {} - } - }, - "response": { - "input": { - "text": "Can you turn off the AC" - }, - "context": { - "conversation_id": "f2c7e362-4cc8-4761-8b0f-9ccd70c63bca", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - }, - "defaultCounter": 0 - }, - "entities": [], - "intents": [{ - "intent": "turn_off", - "confidence": 0.9332477126694649 - }], - "output": { - "log_messages": [], - "text": [ - "Hi. It looks like a nice drive today. What would you like me to do?" - ], - "nodes_visited": ["node_1_1467221909631"] - } - }, - "request_timestamp": "2016-07-16T09:22:38.960Z", - "response_timestamp": "2016-07-16T09:22:39.011Z", - "log_id": "e70d6c12-582d-47a8-a6a2-845120a1f232" - }], - "pagination": { - "next_url": - "/v1/workspaces/15fb0e8a-463d-4fec-86aa-a737d9c38a32/logs?cursor=dOfVSuh6fBpDuOxEL9m1S7JKDV7KLuBmRR+lQG1s1i/rVnBZ0ZBVCuy53ruHgPImC31gQv5prUsJ77e0Mj+6sGu/yfusHYF5&version=2016-07-11&filter=response.top_intent:turn_off&page_limit=1", - "matched": - 215 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - logs = service.list_logs( - workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert logs == response - -@responses.activate -def test_list_all_logs(): - endpoint = '/v1/logs' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "logs": [{ - "request": { - "input": { - "text": "Good morning" - }, - "context": { - "metadata": { - "deployment": "deployment_1" - } - } - }, - "response": { - "intents": [{ - "intent": "hello", - "confidence": 1 - }], - "entities": [], - "input": { - "text": "Good morning" - }, - "output": { - "text": ["Hi! What can I do for you?"], - "nodes_visited": ["node_2_1501875253968"], - "log_messages": [] - }, - "context": { - "metadata": { - "deployment": "deployment_1" - }, - "conversation_id": "81a43b48-7dca-4a7d-a0d7-6fed03fcee69", - "system": { - "dialog_stack": [{ - "dialog_node": "root" - }], - "dialog_turn_counter": 1, - "dialog_request_counter": 1, - "_node_output_map": { - "node_2_1501875253968": [0] - }, - "branch_exited": True, - "branch_exited_reason": "completed" - } - } - }, - "language": "en", - "workspace_id": "9978a49e-ea89-4493-b33d-82298d3db20d", - "request_timestamp": "2017-09-13T19:52:32.611Z", - "response_timestamp": "2017-09-13T19:52:32.628Z", - "log_id": "aa886a8a-bac5-4b91-8323-2fd61a69c9d3" - }], - "pagination": {} - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - logs = service.list_all_logs( - 'language::en,request.context.metadata.deployment::deployment_1').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert logs == response - - -######################### -# message -######################### - - -@responses.activate -def test_message(): - - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) - - workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' - message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' - message_url1 = url1_str % (base_url, workspace_id) - message_response = { - "context": { - "conversation_id": "1b7b67c0-90ed-45dc-8508-9488bc483d5b", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - } - }, - "intents": [], - "entities": [], - "input": {}, - "output": { - "text": "okay", - "log_messages": [] - } - } - - responses.add( - responses.POST, - message_url, - body=json.dumps(message_response), - status=200, - content_type='application/json') - - message = assistant.message( - workspace_id=workspace_id, - input={'text': 'Turn on the lights'}, - context=None).get_result() - - assert message is not None - assert responses.calls[0].request.url == message_url1 - assert 'x-watson-learning-opt-out' in responses.calls[0].request.headers - assert responses.calls[0].request.headers['x-watson-learning-opt-out'] == 'true' - assert responses.calls[0].response.text == json.dumps(message_response) - - # test context - responses.add( - responses.POST, - message_url, - body=message_response, - status=200, - content_type='application/json') - - message_ctx = { - 'context': { - 'conversation_id': '1b7b67c0-90ed-45dc-8508-9488bc483d5b', - 'system': { - 'dialog_stack': ['root'], - 'dialog_turn_counter': 2, - 'dialog_request_counter': 1 - } - } - } - message = assistant.message( - workspace_id=workspace_id, - input={'text': 'Turn on the lights'}, - context=json.dumps(message_ctx['context'])).get_result() - - assert message is not None - assert responses.calls[1].request.url == message_url1 - assert responses.calls[1].response.text == json.dumps(message_response) - - assert len(responses.calls) == 2 - -@responses.activate -def test_message_with_models(): - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) - - workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' - message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' - message_url1 = url1_str % (base_url, workspace_id) - message_response = { - "context": { - "conversation_id": "1b7b67c0-90ed-45dc-8508-9488bc483d5b", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - } - }, - "intents": [], - "entities": [], - "input": {}, - "output": { - "text": "okay", - "log_messages": [] - } - } - - responses.add( - responses.POST, - message_url, - body=json.dumps(message_response), - status=200, - content_type='application/json') - - message = assistant.message( - workspace_id=workspace_id, - input=MessageInput(text='Turn on the lights'), - context=None).get_result() - - assert message is not None - assert responses.calls[0].request.url == message_url1 - assert 'x-watson-learning-opt-out' in responses.calls[0].request.headers - assert responses.calls[0].request.headers['x-watson-learning-opt-out'] == 'true' - assert responses.calls[0].response.text == json.dumps(message_response) - - # test context - responses.add( - responses.POST, - message_url, - body=message_response, - status=200, - content_type='application/json') - - message_ctx = Context._from_dict(message_response['context']) - message = assistant.message( - workspace_id=workspace_id, - input=MessageInput(text='Turn on the lights'), - context=message_ctx).get_result() - - assert message is not None - assert responses.calls[1].request.url == message_url1 - assert responses.calls[1].response.text == json.dumps(message_response) - - assert len(responses.calls) == 2 - - -######################### -# synonyms -######################### - - -@responses.activate -def test_create_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - 'boguswid', 'aeiou', 'vowel') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "aeiou", - "created": "2000-01-23T04:56:07.000+00:00", - "updated": "2000-01-23T04:56:07.000+00:00" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.create_synonym( - workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - -@responses.activate -def test_delete_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'aeiou', 'vowel', 'a') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.delete_synonym( - workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym is None - - -@responses.activate -def test_get_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'grilling', 'bbq', 'barbecue') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.get_synonym( - workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - - -@responses.activate -def test_list_synonyms(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonyms": [{ - "synonym": "BBQ sauce", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values/types/synonyms?version=2017-12-18&filter=name:b&include_count=true&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values/types/synonyms?cursor=base64=&version=2017-12-18&filter=name:b&page_limit=2", - "total": - 8, - "matched": - 2 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonyms = service.list_synonyms( - workspace_id='boguswid', - entity='grilling', - value='bbq').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonyms == response - # Verify that response can be converted to a SynonymCollection - SynonymCollection._from_dict(synonyms) - - -@responses.activate -def test_update_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'grilling', 'bbq', 'barbecue') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.update_synonym( - workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue', new_synonym='barbecue').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - - -######################### -# values -######################### - - -@responses.activate -def test_create_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format('boguswid', 'grilling') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "metadata": "{}", - "created": "2000-01-23T04:56:07.000+00:00", - "value": "aeiou", - "type": "synonyms", - "updated": "2000-01-23T04:56:07.000+00:00" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.create_value( - workspace_id='boguswid', - entity='grilling', - value='aeiou').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -@responses.activate -def test_delete_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = "" - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.delete_value( - workspace_id='boguswid', entity='grilling', value='bbq').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == "" - - -@responses.activate -def test_get_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.get_value( - workspace_id='boguswid', entity='grilling', value='bbq', export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -@responses.activate -def test_list_values(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format('boguswid', 'grilling') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "values": [{ - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values?version=2017-12-18&filter=name:pizza&include_count=true&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/sauce/values?cursor=base64=&version=2017-12-18&filter=name:pizza&page_limit=1", - "total": - 1, - "matched": - 1 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - values = service.list_values( - workspace_id='boguswid', - entity='grilling', - export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert values == response - # Verify that response can be converted to a ValueCollection - ValueCollection._from_dict(values) - - -@responses.activate -def test_update_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-06T23:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.update_value( - workspace_id='boguswid', - entity='grilling', - value='bbq', - new_value='BBQ sauce', - new_metadata={"code": 1422}, - new_synonyms=None).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -######################### -# workspaces -######################### - - -@responses.activate -def test_create_workspace(): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.create_workspace( - name='Pizza app', description='Pizza app', language='en', metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}, - webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - -@responses.activate -def test_delete_workspace(): - endpoint = '/v1/workspaces/{0}'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.delete_workspace(workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace is None - - -@responses.activate -def test_get_workspace(): - endpoint = '/v1/workspaces/{0}'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "status": "Available", - "learning_opt_out": False, - "workspace_id": "pizza_app-e0f3" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.get_workspace(workspace_id='boguswid', export=True, sort='stable').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - - -@responses.activate -def test_list_workspaces(): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "workspaces": [{ - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - }], - "pagination": { - "refresh_url": - "/v1/workspaces?version=2016-01-24&page_limit=1", - "next_url": - "/v1/workspaces?cursor=base64=&version=2016-01-24&page_limit=1" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspaces = service.list_workspaces().get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspaces == response - # Verify that response can be converted to a WorkspaceCollection - WorkspaceCollection._from_dict(workspaces) - - -@responses.activate -def test_update_workspace(): - endpoint = '/v1/workspaces/{0}'.format('pizza_app-e0f3') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.update_workspace( - workspace_id='pizza_app-e0f3', - name='Pizza app', - description='Pizza app', - language='en', - metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}, - webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() - assert len(responses.calls) == 1 + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - -@responses.activate -def test_dialog_nodes(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/id/dialog_nodes' - responses.add( - responses.GET, - url, - body='{ "application/json": { "dialog_node": "location-atm" }}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}/location-done?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-done" }}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-done" }}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/location-done?version=2017-02-03".format(url), - body='{"description": "deleted successfully"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/location-done?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-atm" }}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - assistant.create_dialog_node('id', 'location-done', user_label='xxx', disambiguation_opt_out=False) - assert responses.calls[0].response.json()['application/json']['dialog_node'] == 'location-done' - - assistant.update_dialog_node('id', 'location-done', user_label='xxx', new_disambiguation_opt_out=False) - assert responses.calls[1].response.json()['application/json']['dialog_node'] == 'location-done' - - assistant.delete_dialog_node('id', 'location-done') - assert responses.calls[2].response.json() == {"description": "deleted successfully"} - - assistant.get_dialog_node('id', 'location-done') - assert responses.calls[3].response.json() == {"application/json": {"dialog_node": "location-atm"}} - - assistant.list_dialog_nodes('id') - assert responses.calls[4].response.json() == {"application/json": {"dialog_node": "location-atm"}} - - assert len(responses.calls) == 5 - -@responses.activate -def test_delete_user_data(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body=None, - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - response = service.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - -@responses.activate -def test_list_mentions(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/workspace_id/entities/entity1/mentions' - responses.add( - responses.GET, - url, - body='[{"entity": "xxx"}]', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - response = service.list_mentions('workspace_id', 'entity1').get_result() - assert response == [{"entity": "xxx"}] - assert len(responses.calls) == 1 + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_MessageResponse_json = """{"input": {"text": "fake_text"}, "intents": [], "entities": [], "alternate_intents": false, "context": {"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}, "output": {"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}, "actions": []}""" +fake_response_WorkspaceCollection_json = """{"workspaces": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_IntentCollection_json = """{"intents": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Intent_json = """{"intent": "fake_intent", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_Intent_json = """{"intent": "fake_intent", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_Intent_json = """{"intent": "fake_intent", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_ExampleCollection_json = """{"examples": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_CounterexampleCollection_json = """{"counterexamples": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_EntityCollection_json = """{"entities": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_EntityMentionCollection_json = """{"examples": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_ValueCollection_json = """{"values": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_SynonymCollection_json = """{"synonyms": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNodeCollection_json = """{"dialog_nodes": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" From 4015ec894fb7458047e7fe7b1a9a2f90d8d08031 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:34:34 -0500 Subject: [PATCH 04/28] refactor(assisstantv2): regenerate assistantv2 with tests --- ibm_watson/assistant_v2.py | 793 ++++++++++++++++++++++----------- test/unit/test_assistant_v2.py | 409 +++++++++++++---- 2 files changed, 851 insertions(+), 351 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 6489bfab1..60b838104 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,11 +22,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -36,13 +40,15 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" - default_service_url = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Assistant service. @@ -61,30 +67,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('assistant') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('assistant') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Sessions ######################### - def create_session(self, assistant_id, **kwargs): + def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': """ Create a session. @@ -111,7 +107,9 @@ def create_session(self, assistant_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', '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 = {'version': self.version} @@ -121,12 +119,13 @@ def create_session(self, assistant_id, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_session(self, assistant_id, session_id, **kwargs): + def delete_session(self, assistant_id: str, session_id: str, + **kwargs) -> 'DetailedResponse': """ Delete session. @@ -154,7 +153,9 @@ def delete_session(self, assistant_id, session_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', '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 = {'version': self.version} @@ -164,8 +165,8 @@ def delete_session(self, assistant_id, session_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -174,12 +175,12 @@ def delete_session(self, assistant_id, session_id, **kwargs): ######################### def message(self, - assistant_id, - session_id, + assistant_id: str, + session_id: str, *, - input=None, - context=None, - **kwargs): + input: 'MessageInput' = None, + context: 'MessageContext' = None, + **kwargs) -> 'DetailedResponse': """ Send user input to assistant. @@ -216,7 +217,9 @@ def message(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', 'message') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message') headers.update(sdk_headers) params = {'version': self.version} @@ -229,8 +232,8 @@ def message(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -245,23 +248,23 @@ class CaptureGroup(): CaptureGroup. :attr str group: A recognized capture group for the entity. - :attr list[int] location: (optional) Zero-based character offsets that indicate + :attr 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, *, location=None): + def __init__(self, group: str, *, location: List[int] = None) -> None: """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} valid_keys = ['group', 'location'] @@ -279,7 +282,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup 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, 'group') and self.group is not None: @@ -288,17 +296,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CaptureGroup') -> 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): + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -311,7 +323,7 @@ class DialogLogMessage(): :attr str message: The text of the log message. """ - def __init__(self, level, message): + def __init__(self, level: str, message: str) -> None: """ Initialize a DialogLogMessage object. @@ -322,7 +334,7 @@ def __init__(self, level, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': """Initialize a DialogLogMessage object from a json dictionary.""" args = {} valid_keys = ['level', 'message'] @@ -345,7 +357,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogLogMessage 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, 'level') and self.level is not None: @@ -354,17 +371,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 DialogLogMessage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogLogMessage') -> 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): + def __ne__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -392,12 +413,12 @@ class DialogNodeAction(): """ def __init__(self, - name, - result_variable, + name: str, + result_variable: str, *, - type=None, - parameters=None, - credentials=None): + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ Initialize a DialogNodeAction object. @@ -417,7 +438,7 @@ def __init__(self, self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} valid_keys = [ @@ -448,7 +469,12 @@ def _from_dict(cls, _dict): args['credentials'] = _dict.get('credentials') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeAction 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: @@ -464,17 +490,21 @@ def _to_dict(self): _dict['credentials'] = self.credentials return _dict - def __str__(self): + 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 DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeAction') -> 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): + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -497,7 +527,8 @@ class DialogNodeOutputOptionsElement(): input to be sent to the assistant if the user selects the corresponding option. """ - def __init__(self, label, value): + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -510,7 +541,7 @@ def __init__(self, label, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} valid_keys = ['label', 'value'] @@ -534,7 +565,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElement 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, 'label') and self.label is not None: @@ -543,17 +579,21 @@ def _to_dict(self): _dict['value'] = self.value._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -567,7 +607,7 @@ class DialogNodeOutputOptionsElementValue(): text. """ - def __init__(self, *, input=None): + def __init__(self, *, input: 'MessageInput' = None) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -577,7 +617,7 @@ def __init__(self, *, input=None): self.input = input @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} valid_keys = ['input'] @@ -590,24 +630,33 @@ def _from_dict(cls, _dict): args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElementValue 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: _dict['input'] = self.input._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -622,7 +671,11 @@ class DialogNodesVisited(): :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, *, dialog_node=None, title=None, conditions=None): + def __init__(self, + *, + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ Initialize a DialogNodesVisited object. @@ -637,7 +690,7 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): self.conditions = conditions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodesVisited': """Initialize a DialogNodesVisited object from a json dictionary.""" args = {} valid_keys = ['dialog_node', 'title', 'conditions'] @@ -654,7 +707,12 @@ def _from_dict(cls, _dict): args['conditions'] = _dict.get('conditions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodesVisited 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, 'dialog_node') and self.dialog_node is not None: @@ -665,17 +723,21 @@ def _to_dict(self): _dict['conditions'] = self.conditions return _dict - def __str__(self): + 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 DialogNodesVisited object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodesVisited') -> 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): + def __ne__(self, other: 'DialogNodesVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -694,7 +756,11 @@ class DialogSuggestion(): Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label, value, *, output=None): + def __init__(self, + label: str, + value: 'DialogSuggestionValue', + *, + output: dict = None) -> None: """ Initialize a DialogSuggestion object. @@ -712,7 +778,7 @@ def __init__(self, label, value, *, output=None): self.output = output @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} valid_keys = ['label', 'value', 'output'] @@ -737,7 +803,12 @@ def _from_dict(cls, _dict): args['output'] = _dict.get('output') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestion 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, 'label') and self.label is not None: @@ -748,17 +819,21 @@ def _to_dict(self): _dict['output'] = self.output return _dict - def __str__(self): + 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 DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestion') -> 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): + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -772,7 +847,7 @@ class DialogSuggestionValue(): text. """ - def __init__(self, *, input=None): + def __init__(self, *, input: 'MessageInput' = None) -> None: """ Initialize a DialogSuggestionValue object. @@ -782,7 +857,7 @@ def __init__(self, *, input=None): self.input = input @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} valid_keys = ['input'] @@ -795,24 +870,33 @@ def _from_dict(cls, _dict): args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionValue 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: _dict['input'] = self.input._to_dict() return _dict - def __str__(self): + 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 DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionValue') -> 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): + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -830,7 +914,10 @@ class MessageContext(): assistant. """ - def __init__(self, *, global_=None, skills=None): + def __init__(self, + *, + global_: 'MessageContextGlobal' = None, + skills: 'MessageContextSkills' = None) -> None: """ Initialize a MessageContext object. @@ -846,7 +933,7 @@ def __init__(self, *, global_=None, skills=None): self.skills = skills @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContext': """Initialize a MessageContext object from a json dictionary.""" args = {} valid_keys = ['global_', 'global', 'skills'] @@ -863,7 +950,12 @@ def _from_dict(cls, _dict): _dict.get('skills')) return cls(**args) - def _to_dict(self): + @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: @@ -872,17 +964,21 @@ def _to_dict(self): _dict['skills'] = self.skills._to_dict() return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -895,7 +991,7 @@ class MessageContextGlobal(): that apply to all skills used by the assistant. """ - def __init__(self, *, system=None): + def __init__(self, *, system: 'MessageContextGlobalSystem' = None) -> None: """ Initialize a MessageContextGlobal object. @@ -905,7 +1001,7 @@ def __init__(self, *, system=None): self.system = system @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} valid_keys = ['system'] @@ -919,24 +1015,33 @@ def _from_dict(cls, _dict): _dict.get('system')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """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, 'system') and self.system is not None: _dict['system'] = self.system._to_dict() return _dict - def __str__(self): + 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 MessageContextGlobal object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + 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): + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -958,7 +1063,11 @@ class MessageContextGlobalSystem(): (for example, triggering the start node of a dialog). """ - def __init__(self, *, timezone=None, user_id=None, turn_count=None): + def __init__(self, + *, + timezone: str = None, + user_id: str = None, + turn_count: int = None) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -981,7 +1090,7 @@ def __init__(self, *, timezone=None, user_id=None, turn_count=None): self.turn_count = turn_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} valid_keys = ['timezone', 'user_id', 'turn_count'] @@ -998,7 +1107,12 @@ def _from_dict(cls, _dict): args['turn_count'] = _dict.get('turn_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """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, 'timezone') and self.timezone is not None: @@ -1009,17 +1123,21 @@ def _to_dict(self): _dict['turn_count'] = self.turn_count return _dict - def __str__(self): + 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 MessageContextGlobalSystem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + 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): + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1030,22 +1148,26 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. + :attr dict system: (optional) For internal use only. """ - def __init__(self, *, user_defined=None): + def __init__(self, *, user_defined: dict = None, + system: dict = None) -> None: """ Initialize a MessageContextSkill object. :param dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. + :param dict system: (optional) For internal use only. """ self.user_defined = user_defined + self.system = system @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - valid_keys = ['user_defined'] + valid_keys = ['user_defined', 'system'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1053,26 +1175,39 @@ def _from_dict(cls, _dict): + ', '.join(bad_keys)) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = _dict.get('system') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkill 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: + _dict['system'] = self.system return _dict - def __str__(self): + 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 MessageContextSkill object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextSkill') -> 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): + def __ne__(self, other: 'MessageContextSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1085,7 +1220,7 @@ class MessageContextSkills(): """ - def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """ Initialize a MessageContextSkills object. @@ -1095,14 +1230,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': """Initialize a MessageContextSkills object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @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, '_additionalProperties'): @@ -1112,7 +1252,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(MessageContextSkills, @@ -1121,17 +1265,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(MessageContextSkills, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + 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): + def __ne__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1146,10 +1290,10 @@ class MessageInput(): contain carriage return, newline, or tab characters. :attr MessageInputOptions options: (optional) Optional properties that control how the assistant responds. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + :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 + :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. @@ -1157,12 +1301,12 @@ class MessageInput(): def __init__(self, *, - message_type=None, - text=None, - options=None, - intents=None, - entities=None, - suggestion_id=None): + message_type: str = None, + text: str = None, + options: 'MessageInputOptions' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None) -> None: """ Initialize a MessageInput object. @@ -1172,11 +1316,11 @@ def __init__(self, contain carriage return, newline, or tab characters. :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :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 + :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. @@ -1190,7 +1334,7 @@ def __init__(self, self.suggestion_id = suggestion_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} valid_keys = [ @@ -1221,7 +1365,12 @@ def _from_dict(cls, _dict): args['suggestion_id'] = _dict.get('suggestion_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput 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: @@ -1238,17 +1387,21 @@ def _to_dict(self): _dict['suggestion_id'] = self.suggestion_id return _dict - def __str__(self): + 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 MessageInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInput') -> 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): + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1278,10 +1431,10 @@ class MessageInputOptions(): def __init__(self, *, - debug=None, - restart=None, - alternate_intents=None, - return_context=None): + debug: bool = None, + restart: bool = None, + alternate_intents: bool = None, + return_context: bool = None) -> None: """ Initialize a MessageInputOptions object. @@ -1303,7 +1456,7 @@ def __init__(self, self.return_context = return_context @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} valid_keys = ['debug', 'restart', 'alternate_intents', 'return_context'] @@ -1322,7 +1475,12 @@ def _from_dict(cls, _dict): args['return_context'] = _dict.get('return_context') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptions 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, 'debug') and self.debug is not None: @@ -1336,17 +1494,21 @@ def _to_dict(self): _dict['return_context'] = self.return_context return _dict - def __str__(self): + 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 MessageInputOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInputOptions') -> 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): + def __ne__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1355,14 +1517,14 @@ class MessageOutput(): """ Assistant output to be rendered or processed by the client. - :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + :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 + :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 + :attr List[RuntimeEntity] entities: (optional) An array of entities identified in the user input. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :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. @@ -1373,23 +1535,23 @@ class MessageOutput(): def __init__(self, *, - generic=None, - intents=None, - entities=None, - actions=None, - debug=None, - user_defined=None): + generic: List['RuntimeResponseGeneric'] = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + actions: List['DialogNodeAction'] = None, + debug: 'MessageOutputDebug' = None, + user_defined: dict = None) -> None: """ Initialize a MessageOutput object. - :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + :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 + :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 + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the user input. - :param list[DialogNodeAction] actions: (optional) An array of objects + :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. @@ -1406,7 +1568,7 @@ def __init__(self, self.user_defined = user_defined @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageOutput': """Initialize a MessageOutput object from a json dictionary.""" args = {} valid_keys = [ @@ -1440,7 +1602,12 @@ def _from_dict(cls, _dict): args['user_defined'] = _dict.get('user_defined') return cls(**args) - def _to_dict(self): + @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: @@ -1457,17 +1624,21 @@ def _to_dict(self): _dict['user_defined'] = self.user_defined return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1476,10 +1647,10 @@ class MessageOutputDebug(): """ Additional detailed information about a message response and how it was generated. - :attr list[DialogNodesVisited] nodes_visited: (optional) An array of objects + :attr List[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. - :attr list[DialogLogMessage] log_messages: (optional) An array of up to 50 + :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. @@ -1490,17 +1661,17 @@ class MessageOutputDebug(): def __init__(self, *, - nodes_visited=None, - log_messages=None, - branch_exited=None, - branch_exited_reason=None): + nodes_visited: List['DialogNodesVisited'] = None, + log_messages: List['DialogLogMessage'] = None, + branch_exited: bool = None, + branch_exited_reason: str = None) -> None: """ Initialize a MessageOutputDebug object. - :param list[DialogNodesVisited] nodes_visited: (optional) An array of + :param List[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. - :param list[DialogLogMessage] log_messages: (optional) An array of up to 50 + :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. @@ -1514,7 +1685,7 @@ def __init__(self, self.branch_exited_reason = branch_exited_reason @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} valid_keys = [ @@ -1542,7 +1713,12 @@ def _from_dict(cls, _dict): args['branch_exited_reason'] = _dict.get('branch_exited_reason') return cls(**args) - def _to_dict(self): + @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: @@ -1556,17 +1732,21 @@ def _to_dict(self): _dict['branch_exited_reason'] = self.branch_exited_reason return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1592,7 +1772,10 @@ class MessageResponse(): **return_context**=`true` in the message request. """ - def __init__(self, output, *, context=None): + def __init__(self, + output: 'MessageOutput', + *, + context: 'MessageContext' = None) -> None: """ Initialize a MessageResponse object. @@ -1608,7 +1791,7 @@ def __init__(self, output, *, context=None): self.context = context @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} valid_keys = ['output', 'context'] @@ -1627,7 +1810,12 @@ def _from_dict(cls, _dict): args['context'] = MessageContext._from_dict(_dict.get('context')) return cls(**args) - def _to_dict(self): + @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: @@ -1636,17 +1824,21 @@ def _to_dict(self): _dict['context'] = self.context._to_dict() return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1656,37 +1848,37 @@ 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: An array of zero-based character offsets that indicate + :attr List[int] location: 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 value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. :attr dict metadata: (optional) Any metadata for the entity. - :attr list[CaptureGroup] groups: (optional) The recognized capture groups for + :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, - entity, - location, - value, + entity: str, + location: List[int], + value: str, *, - confidence=None, - metadata=None, - groups=None): + confidence: float = None, + metadata: dict = None, + groups: List['CaptureGroup'] = None) -> None: """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: The term in the input text that was recognized as an entity value. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. :param dict metadata: (optional) Any metadata for the entity. - :param list[CaptureGroup] groups: (optional) The recognized capture groups + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ self.entity = entity @@ -1697,7 +1889,7 @@ def __init__(self, self.groups = groups @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -1735,7 +1927,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: @@ -1752,17 +1949,21 @@ def _to_dict(self): _dict['groups'] = [x._to_dict() for x in self.groups] return _dict - def __str__(self): + 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 RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeEntity') -> 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): + def __ne__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1776,7 +1977,7 @@ class RuntimeIntent(): in the intent. """ - def __init__(self, intent, confidence): + def __init__(self, intent: str, confidence: float) -> None: """ Initialize a RuntimeIntent object. @@ -1788,7 +1989,7 @@ def __init__(self, intent, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'confidence'] @@ -1811,7 +2012,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: @@ -1820,17 +2026,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeIntent') -> 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): + def __ne__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1852,38 +2062,38 @@ class RuntimeResponseGeneric(): 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: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects + :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. :attr str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. - :attr list[SearchResult] results: (optional) An array of objects containing + :attr List[SearchResult] results: (optional) An array of objects containing search results. """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - suggestions=None, - header=None, - results=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + suggestions: List['DialogSuggestion'] = None, + header: str = None, + results: List['SearchResult'] = None) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -1902,21 +2112,21 @@ def __init__(self, :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: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. - :param list[DialogSuggestion] suggestions: (optional) An array of objects + :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. :param str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. - :param list[SearchResult] results: (optional) An array of objects + :param List[SearchResult] results: (optional) An array of objects containing search results. """ self.response_type = response_type @@ -1935,7 +2145,7 @@ def __init__(self, self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -1990,7 +2200,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -2024,17 +2239,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 RuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeResponseGeneric') -> 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): + def __ne__(self, other: 'RuntimeResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2085,13 +2304,13 @@ class SearchResult(): """ def __init__(self, - id, - result_metadata, + id: str, + result_metadata: 'SearchResultMetadata', *, - body=None, - title=None, - url=None, - highlight=None): + body: str = None, + title: str = None, + url: str = None, + highlight: 'SearchResultHighlight' = None) -> None: """ Initialize a SearchResult object. @@ -2121,7 +2340,7 @@ def __init__(self, self.highlight = highlight @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResult': """Initialize a SearchResult object from a json dictionary.""" args = {} valid_keys = [ @@ -2155,7 +2374,12 @@ def _from_dict(cls, _dict): _dict.get('highlight')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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: @@ -2173,17 +2397,21 @@ def _to_dict(self): _dict['highlight'] = self.highlight._to_dict() return _dict - def __str__(self): + 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 SearchResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResult') -> 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): + def __ne__(self, other: 'SearchResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2193,27 +2421,32 @@ 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 + :attr 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 + :attr 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 + :attr List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. """ - def __init__(self, *, body=None, title=None, url=None, **kwargs): + def __init__(self, + *, + body: List[str] = None, + title: List[str] = None, + url: List[str] = None, + **kwargs) -> None: """ Initialize a SearchResultHighlight object. - :param list[str] body: (optional) An array of strings containing segments + :param List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings highlighted. - :param list[str] title: (optional) An array of strings containing segments + :param List[str] title: (optional) An array of strings containing segments taken from title text in the search results, with query-matching substrings highlighted. - :param list[str] url: (optional) An array of strings containing segments + :param List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. :param **kwargs: (optional) Any additional properties. @@ -2225,7 +2458,7 @@ def __init__(self, *, body=None, title=None, url=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -2241,7 +2474,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: @@ -2257,7 +2495,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'body', 'title', 'url'} if not hasattr(self, '_additionalProperties'): super(SearchResultHighlight, @@ -2266,17 +2508,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(SearchResultHighlight, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this SearchResultHighlight object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResultHighlight') -> 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): + def __ne__(self, other: 'SearchResultHighlight') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2293,7 +2535,8 @@ class SearchResultMetadata(): indicates a greater match to the query parameters. """ - def __init__(self, *, confidence=None, score=None): + def __init__(self, *, confidence: float = None, + score: float = None) -> None: """ Initialize a SearchResultMetadata object. @@ -2308,7 +2551,7 @@ def __init__(self, *, confidence=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} valid_keys = ['confidence', 'score'] @@ -2323,7 +2566,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: @@ -2332,17 +2580,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 SearchResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResultMetadata') -> 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): + def __ne__(self, other: 'SearchResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2354,7 +2606,7 @@ class SessionResponse(): :attr str session_id: The session ID. """ - def __init__(self, session_id): + def __init__(self, session_id: str) -> None: """ Initialize a SessionResponse object. @@ -2363,7 +2615,7 @@ def __init__(self, session_id): self.session_id = session_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SessionResponse': """Initialize a SessionResponse object from a json dictionary.""" args = {} valid_keys = ['session_id'] @@ -2380,23 +2632,32 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id return _dict - def __str__(self): + 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 SessionResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SessionResponse') -> 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): + def __ne__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index d2b3ad534..a43dd8c1b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,88 +1,327 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import ibm_watson -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/assistant/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -@responses.activate -def test_create_session(): - endpoint = '/v2/assistants/{0}/sessions'.format('bogus_id') - url = '{0}{1}'.format(base_url, endpoint) - response = {'session_id': 'session_id'} - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - session = service.create_session('bogus_id').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert session == response - - -@responses.activate -def test_delete_session(): - endpoint = '/v2/assistants/{0}/sessions/{1}'.format('bogus_id', - 'session_id') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - delete_session = service.delete_session('bogus_id', - 'session_id').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert delete_session == response - - -@responses.activate -def test_message(): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format( - 'bogus_id', 'session_id') - url = '{0}{1}'.format(base_url, endpoint) - response = { - 'output': { - 'generic': [{ - 'text': - 'I did not understand that. I can help you get pizza, tell a joke or find a movie.', - 'response_type': - 'text' - }], - 'entities': [], - 'intents': [{ - 'confidence': 0.8521236419677736, - 'intent': 'Weather' - }] - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - message = service.message( - 'bogus_id', 'session_id', input={ - 'text': 'What\'s the weather like?' - }).get_result() - assert len(responses.calls) == 1 +import ibm_watson.assistant_v2 +from ibm_watson.assistant_v2 import * + +base_url = 'https://gateway.watsonplatform.net/assistant/api' + +############################################################################## +# Start of Service: Sessions +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_session +#----------------------------------------------------------------------------- +class TestCreateSession(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_session_response(self): + body = self.construct_full_body() + response = fake_response_SessionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_session_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SessionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_session_empty(self): + check_empty_required_params(self, fake_response_SessionResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/sessions'.format(body['assistant_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_session(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_session +#----------------------------------------------------------------------------- +class TestDeleteSession(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_session_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_session_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_session_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_session(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Sessions +############################################################################## + +############################################################################## +# Start of Service: Message +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for message +#----------------------------------------------------------------------------- +class TestMessage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_response(self): + body = self.construct_full_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_empty(self): + check_empty_required_params(self, fake_response_MessageResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.message(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Message +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) assert responses.calls[0].request.url.startswith(url) - assert message == response + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_SessionResponse_json = """{"session_id": "fake_session_id"}""" +fake_response_MessageResponse_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}}""" From 54ccee6d64b2fadaff201873e464dcdfc256089c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:52:47 -0500 Subject: [PATCH 05/28] refactor(cnc): regenerate compare and comply with tests --- ibm_watson/compare_comply_v1.py | 2172 +++++++++++++++++---------- test/unit/test_compare_comply_v1.py | 1606 +++++++++++++------- 2 files changed, 2433 insertions(+), 1345 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 9b45d0840..9266c3ffa 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,21 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import date +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -34,13 +43,15 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_NAME = 'compare-comply' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Compare Comply service. @@ -59,41 +70,31 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('compare_comply') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('compare_comply') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # HTML conversion ######################### def convert_to_html(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Convert document to HTML. Converts a document to HTML. - :param file file: The document to convert. + :param TextIO file: The document to convert. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -111,7 +112,9 @@ def convert_to_html(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'convert_to_html') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='convert_to_html') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -125,8 +128,8 @@ def convert_to_html(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -135,17 +138,17 @@ def convert_to_html(self, ######################### def classify_elements(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Classify the elements of a document. Analyzes the structural and semantic elements of a document. - :param file file: The document to classify. + :param TextIO file: The document to classify. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -163,8 +166,9 @@ def classify_elements(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', - 'classify_elements') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify_elements') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -178,8 +182,8 @@ def classify_elements(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -188,17 +192,17 @@ def classify_elements(self, ######################### def extract_tables(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Extract a document's tables. Analyzes the tables in a document. - :param file file: The document on which to run table extraction. + :param TextIO file: The document on which to run table extraction. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -216,7 +220,9 @@ def extract_tables(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'extract_tables') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='extract_tables') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -230,8 +236,8 @@ def extract_tables(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -240,22 +246,22 @@ def extract_tables(self, ######################### def compare_documents(self, - file_1, - file_2, + file_1: BinaryIO, + file_2: BinaryIO, *, - file_1_content_type=None, - file_2_content_type=None, - file_1_label=None, - file_2_label=None, - model=None, - **kwargs): + file_1_content_type: str = None, + file_2_content_type: str = None, + file_1_label: str = None, + file_2_label: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Compare two documents. Compares two input documents. Documents must be in the same format. - :param file file_1: The first document to compare. - :param file file_2: The second document to compare. + :param TextIO file_1: The first document to compare. + :param TextIO file_2: The second document to compare. :param str file_1_content_type: (optional) The content type of file_1. :param str file_2_content_type: (optional) The content type of file_2. :param str file_1_label: (optional) A text label for the first document. @@ -278,8 +284,9 @@ def compare_documents(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', - 'compare_documents') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='compare_documents') headers.update(sdk_headers) params = { @@ -300,8 +307,8 @@ def compare_documents(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -310,11 +317,11 @@ def compare_documents(self, ######################### def add_feedback(self, - feedback_data, + feedback_data: 'FeedbackDataInput', *, - user_id=None, - comment=None, - **kwargs): + user_id: str = None, + comment: str = None, + **kwargs) -> 'DetailedResponse': """ Add feedback. @@ -340,7 +347,9 @@ def add_feedback(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'add_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_feedback') headers.update(sdk_headers) params = {'version': self.version} @@ -356,30 +365,30 @@ def add_feedback(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def list_feedback(self, *, - feedback_type=None, - before=None, - after=None, - document_title=None, - model_id=None, - model_version=None, - category_removed=None, - category_added=None, - category_not_changed=None, - type_removed=None, - type_added=None, - type_not_changed=None, - page_limit=None, - cursor=None, - sort=None, - include_total=None, - **kwargs): + feedback_type: str = None, + before: date = None, + after: date = None, + document_title: str = None, + model_id: str = None, + model_version: str = None, + category_removed: str = None, + category_added: str = None, + category_not_changed: str = None, + type_removed: str = None, + type_added: str = None, + type_not_changed: str = None, + page_limit: int = None, + cursor: str = None, + sort: str = None, + include_total: bool = None, + **kwargs) -> 'DetailedResponse': """ List the feedback in a document. @@ -447,7 +456,9 @@ def list_feedback(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'list_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_feedback') headers.update(sdk_headers) params = { @@ -474,12 +485,13 @@ def list_feedback(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_feedback(self, feedback_id, *, model=None, **kwargs): + def get_feedback(self, feedback_id: str, *, model: str = None, + **kwargs) -> 'DetailedResponse': """ Get a specified feedback entry. @@ -503,7 +515,9 @@ def get_feedback(self, feedback_id, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'get_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_feedback') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -512,12 +526,13 @@ def get_feedback(self, feedback_id, *, model=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_feedback(self, feedback_id, *, model=None, **kwargs): + def delete_feedback(self, feedback_id: str, *, model: str = None, + **kwargs) -> 'DetailedResponse': """ Delete a specified feedback entry. @@ -541,7 +556,9 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'delete_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_feedback') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -550,8 +567,8 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -560,16 +577,16 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): ######################### def create_batch(self, - function, - input_credentials_file, - input_bucket_location, - input_bucket_name, - output_credentials_file, - output_bucket_location, - output_bucket_name, + function: str, + input_credentials_file: BinaryIO, + input_bucket_location: str, + input_bucket_name: str, + output_credentials_file: BinaryIO, + output_bucket_location: str, + output_bucket_name: str, *, - model=None, - **kwargs): + model: str = None, + **kwargs) -> 'DetailedResponse': """ Submit a batch-processing request. @@ -582,8 +599,8 @@ def create_batch(self, :param str function: The Compare and Comply method to run across the submitted input documents. - :param file input_credentials_file: A JSON file containing the input Cloud - Object Storage credentials. At a minimum, the credentials must enable + :param TextIO input_credentials_file: A JSON file containing the input + Cloud Object Storage credentials. At a minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name` parameter. :param str input_bucket_location: The geographical location of the Cloud @@ -591,7 +608,7 @@ def create_batch(self, Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str input_bucket_name: The name of the Cloud Object Storage input bucket. - :param file output_credentials_file: A JSON file that lists the Cloud + :param TextIO output_credentials_file: A JSON file that lists the Cloud Object Storage output credentials. At a minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the `output_bucket_name` parameter. @@ -629,7 +646,9 @@ def create_batch(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'create_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_batch') headers.update(sdk_headers) params = {'version': self.version, 'function': function, 'model': model} @@ -637,14 +656,18 @@ def create_batch(self, form_data = [] form_data.append(('input_credentials_file', (None, input_credentials_file, 'application/json'))) + input_bucket_location = str(input_bucket_location) form_data.append(('input_bucket_location', (None, input_bucket_location, 'text/plain'))) + input_bucket_name = str(input_bucket_name) form_data.append( ('input_bucket_name', (None, input_bucket_name, 'text/plain'))) form_data.append(('output_credentials_file', (None, output_credentials_file, 'application/json'))) + output_bucket_location = str(output_bucket_location) form_data.append(('output_bucket_location', (None, output_bucket_location, 'text/plain'))) + output_bucket_name = str(output_bucket_name) form_data.append( ('output_bucket_name', (None, output_bucket_name, 'text/plain'))) @@ -653,12 +676,12 @@ def create_batch(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_batches(self, **kwargs): + def list_batches(self, **kwargs) -> 'DetailedResponse': """ List submitted batch-processing jobs. @@ -672,7 +695,9 @@ def list_batches(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'list_batches') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_batches') headers.update(sdk_headers) params = {'version': self.version} @@ -681,12 +706,12 @@ def list_batches(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_batch(self, batch_id, **kwargs): + def get_batch(self, batch_id: str, **kwargs) -> 'DetailedResponse': """ Get information about a specific batch-processing job. @@ -705,7 +730,9 @@ def get_batch(self, batch_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'get_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_batch') headers.update(sdk_headers) params = {'version': self.version} @@ -714,12 +741,17 @@ def get_batch(self, batch_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def update_batch(self, batch_id, action, *, model=None, **kwargs): + def update_batch(self, + batch_id: str, + action: str, + *, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Update a pending or active batch-processing job. @@ -747,7 +779,9 @@ def update_batch(self, batch_id, action, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'update_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_batch') headers.update(sdk_headers) params = {'version': self.version, 'action': action, 'model': model} @@ -756,8 +790,8 @@ def update_batch(self, batch_id, action, *, model=None, **kwargs): request = self.prepare_request(method='PUT', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -965,7 +999,8 @@ class Address(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Address object. @@ -978,7 +1013,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Address': """Initialize a Address object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -993,7 +1028,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Address 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: @@ -1002,17 +1042,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Address object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Address') -> 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): + def __ne__(self, other: 'Address') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1021,13 +1065,13 @@ class AlignedElement(): """ AlignedElement. - :attr list[ElementPair] element_pair: (optional) Identifies two elements that + :attr List[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :attr bool identical_text: (optional) Specifies whether the aligned element is identical. Elements are considered identical despite minor differences such as leading punctuation, end-of-sentence punctuation, whitespace, the presence or absence of definite or indefinite articles, and others. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. @@ -1035,21 +1079,21 @@ class AlignedElement(): def __init__(self, *, - element_pair=None, - identical_text=None, - provenance_ids=None, - significant_elements=None): + element_pair: List['ElementPair'] = None, + identical_text: bool = None, + provenance_ids: List[str] = None, + significant_elements: bool = None) -> None: """ Initialize a AlignedElement object. - :param list[ElementPair] element_pair: (optional) Identifies two elements + :param List[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :param bool identical_text: (optional) Specifies whether the aligned element is identical. Elements are considered identical despite minor differences such as leading punctuation, end-of-sentence punctuation, whitespace, the presence or absence of definite or indefinite articles, and others. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. @@ -1060,7 +1104,7 @@ def __init__(self, self.significant_elements = significant_elements @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AlignedElement': """Initialize a AlignedElement object from a json dictionary.""" args = {} valid_keys = [ @@ -1084,7 +1128,12 @@ def _from_dict(cls, _dict): args['significant_elements'] = _dict.get('significant_elements') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AlignedElement 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, 'element_pair') and self.element_pair is not None: @@ -1098,17 +1147,21 @@ def _to_dict(self): _dict['significant_elements'] = self.significant_elements return _dict - def __str__(self): + 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 AlignedElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AlignedElement') -> 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): + def __ne__(self, other: 'AlignedElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1124,7 +1177,11 @@ class Attribute(): `end`. """ - def __init__(self, *, type=None, text=None, location=None): + def __init__(self, + *, + type: str = None, + text: str = None, + location: 'Location' = None) -> None: """ Initialize a Attribute object. @@ -1139,7 +1196,7 @@ def __init__(self, *, type=None, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Attribute': """Initialize a Attribute object from a json dictionary.""" args = {} valid_keys = ['type', 'text', 'location'] @@ -1156,7 +1213,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Attribute 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, 'type') and self.type is not None: @@ -1167,17 +1229,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Attribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Attribute') -> 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): + def __ne__(self, other: 'Attribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1222,16 +1288,16 @@ class BatchStatus(): def __init__(self, *, - function=None, - input_bucket_location=None, - input_bucket_name=None, - output_bucket_location=None, - output_bucket_name=None, - batch_id=None, - document_counts=None, - status=None, - created=None, - updated=None): + function: str = None, + input_bucket_location: str = None, + input_bucket_name: str = None, + output_bucket_location: str = None, + output_bucket_name: str = None, + batch_id: str = None, + document_counts: 'DocCounts' = None, + status: str = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a BatchStatus object. @@ -1268,7 +1334,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'BatchStatus': """Initialize a BatchStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -1304,7 +1370,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a BatchStatus 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, 'function') and self.function is not None: @@ -1335,17 +1406,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 BatchStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'BatchStatus') -> 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): + def __ne__(self, other: 'BatchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1363,21 +1438,21 @@ class Batches(): """ The results of a successful **List Batches** request. - :attr list[BatchStatus] batches: (optional) A list of the status of all batch + :attr List[BatchStatus] batches: (optional) A list of the status of all batch requests. """ - def __init__(self, *, batches=None): + def __init__(self, *, batches: List['BatchStatus'] = None) -> None: """ Initialize a Batches object. - :param list[BatchStatus] batches: (optional) A list of the status of all + :param List[BatchStatus] batches: (optional) A list of the status of all batch requests. """ self.batches = batches @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Batches': """Initialize a Batches object from a json dictionary.""" args = {} valid_keys = ['batches'] @@ -1392,24 +1467,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Batches 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, 'batches') and self.batches is not None: _dict['batches'] = [x._to_dict() for x in self.batches] return _dict - def __str__(self): + 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 Batches object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Batches') -> 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): + def __ne__(self, other: 'Batches') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1432,39 +1516,39 @@ class BodyCells(): `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr list[str] row_header_ids: (optional) An array that contains the `id` value + :attr List[str] row_header_ids: (optional) An array that contains the `id` value of a row header that is applicable to this body cell. - :attr list[str] row_header_texts: (optional) An array that contains the `text` + :attr List[str] row_header_texts: (optional) An array that contains the `text` value of a row header that is applicable to this body cell. - :attr list[str] row_header_texts_normalized: (optional) If you provide + :attr List[str] row_header_texts_normalized: (optional) 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 list[str] column_header_ids: (optional) An array that contains the `id` + :attr List[str] column_header_ids: (optional) An array that contains the `id` value of a column header that is applicable to the current cell. - :attr list[str] column_header_texts: (optional) An array that contains the + :attr List[str] column_header_texts: (optional) An array that contains the `text` value of a column header that is applicable to the current cell. - :attr list[str] column_header_texts_normalized: (optional) If you provide + :attr List[str] column_header_texts_normalized: (optional) 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 list[Attribute] attributes: (optional) + :attr List[Attribute] attributes: (optional) """ def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None, - row_header_ids=None, - row_header_texts=None, - row_header_texts_normalized=None, - column_header_ids=None, - column_header_texts=None, - column_header_texts_normalized=None, - attributes=None): + cell_id: str = None, + location: 'Location' = 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[str] = None, + row_header_texts: List[str] = None, + row_header_texts_normalized: List[str] = None, + column_header_ids: List[str] = None, + column_header_texts: List[str] = None, + column_header_texts_normalized: List[str] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a BodyCells object. @@ -1483,23 +1567,23 @@ 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[str] row_header_ids: (optional) An array that contains the `id` + :param List[str] row_header_ids: (optional) An array that contains the `id` value of a row header that is applicable to this body cell. - :param list[str] row_header_texts: (optional) An array that contains the + :param List[str] row_header_texts: (optional) An array that contains the `text` value of a row header that is applicable to this body cell. - :param list[str] row_header_texts_normalized: (optional) If you provide + :param List[str] row_header_texts_normalized: (optional) 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`. - :param list[str] column_header_ids: (optional) An array that contains the + :param List[str] column_header_ids: (optional) An array that contains the `id` value of a column header that is applicable to the current cell. - :param list[str] column_header_texts: (optional) An array that contains the + :param List[str] column_header_texts: (optional) An array that contains the `text` value of a column header that is applicable to the current cell. - :param list[str] column_header_texts_normalized: (optional) If you provide + :param List[str] column_header_texts_normalized: (optional) 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`. - :param list[Attribute] attributes: (optional) + :param List[Attribute] attributes: (optional) """ self.cell_id = cell_id self.location = location @@ -1517,7 +1601,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'BodyCells': """Initialize a BodyCells object from a json dictionary.""" args = {} valid_keys = [ @@ -1566,7 +1650,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a BodyCells 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, 'cell_id') and self.cell_id is not None: @@ -1611,17 +1700,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 BodyCells object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'BodyCells') -> 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): + def __ne__(self, other: 'BodyCells') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1631,23 +1724,24 @@ class Category(): Information defining an element's subject matter. :attr str label: (optional) The category of the associated element. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ - def __init__(self, *, label=None, provenance_ids=None): + def __init__(self, *, label: str = None, + provenance_ids: List[str] = None) -> None: """ Initialize a Category object. :param str label: (optional) The category of the associated element. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Category': """Initialize a Category object from a json dictionary.""" args = {} valid_keys = ['label', 'provenance_ids'] @@ -1662,7 +1756,12 @@ def _from_dict(cls, _dict): args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Category 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, 'label') and self.label is not None: @@ -1671,17 +1770,21 @@ def _to_dict(self): _dict['provenance_ids'] = self.provenance_ids return _dict - def __str__(self): + 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 Category object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Category') -> 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): + def __ne__(self, other: 'Category') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1723,7 +1826,7 @@ class CategoryComparison(): :attr str label: (optional) The category of the associated element. """ - def __init__(self, *, label=None): + def __init__(self, *, label: str = None) -> None: """ Initialize a CategoryComparison object. @@ -1732,7 +1835,7 @@ def __init__(self, *, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoryComparison': """Initialize a CategoryComparison object from a json dictionary.""" args = {} valid_keys = ['label'] @@ -1745,24 +1848,33 @@ def _from_dict(cls, _dict): args['label'] = _dict.get('label') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoryComparison 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, 'label') and self.label is not None: _dict['label'] = self.label return _dict - def __str__(self): + 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 CategoryComparison object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoryComparison') -> 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): + def __ne__(self, other: 'CategoryComparison') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1807,47 +1919,47 @@ class ClassifyReturn(): `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :attr list[Element] elements: (optional) Document elements identified by the + :attr List[Element] elements: (optional) Document elements identified by the service. - :attr list[EffectiveDates] effective_dates: (optional) The date or dates on + :attr List[EffectiveDates] effective_dates: (optional) The date or dates on which the document becomes effective. - :attr list[ContractAmts] contract_amounts: (optional) The monetary amounts that + :attr List[ContractAmts] contract_amounts: (optional) The monetary amounts that identify the total amount of the contract that needs to be paid from one party to another. - :attr list[TerminationDates] termination_dates: (optional) The dates on which + :attr List[TerminationDates] termination_dates: (optional) The dates on which the document is to be terminated. - :attr list[ContractTypes] contract_types: (optional) The contract type as + :attr List[ContractTypes] contract_types: (optional) The contract type as declared in the document. - :attr list[ContractTerms] contract_terms: (optional) The durations of the + :attr List[ContractTerms] contract_terms: (optional) The durations of the contract. - :attr list[PaymentTerms] payment_terms: (optional) The document's payment + :attr List[PaymentTerms] payment_terms: (optional) The document's payment durations. - :attr list[ContractCurrencies] contract_currencies: (optional) The contract + :attr List[ContractCurrencies] contract_currencies: (optional) The contract currencies as declared in the document. - :attr list[Tables] tables: (optional) Definition of tables identified in the + :attr List[Tables] tables: (optional) Definition of tables identified in the input document. :attr DocStructure document_structure: (optional) The structure of the input document. - :attr list[Parties] parties: (optional) Definitions of the parties identified in + :attr List[Parties] parties: (optional) Definitions of the parties identified in the input document. """ def __init__(self, *, - document=None, - model_id=None, - model_version=None, - elements=None, - effective_dates=None, - contract_amounts=None, - termination_dates=None, - contract_types=None, - contract_terms=None, - payment_terms=None, - contract_currencies=None, - tables=None, - document_structure=None, - parties=None): + document: 'Document' = None, + model_id: str = None, + model_version: str = None, + elements: List['Element'] = None, + effective_dates: List['EffectiveDates'] = None, + contract_amounts: List['ContractAmts'] = None, + termination_dates: List['TerminationDates'] = None, + contract_types: List['ContractTypes'] = None, + contract_terms: List['ContractTerms'] = None, + payment_terms: List['PaymentTerms'] = None, + contract_currencies: List['ContractCurrencies'] = None, + tables: List['Tables'] = None, + document_structure: 'DocStructure' = None, + parties: List['Parties'] = None) -> None: """ Initialize a ClassifyReturn object. @@ -1858,28 +1970,28 @@ def __init__(self, value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :param list[Element] elements: (optional) Document elements identified by + :param List[Element] elements: (optional) Document elements identified by the service. - :param list[EffectiveDates] effective_dates: (optional) The date or dates + :param List[EffectiveDates] effective_dates: (optional) The date or dates on which the document becomes effective. - :param list[ContractAmts] contract_amounts: (optional) The monetary amounts + :param List[ContractAmts] contract_amounts: (optional) The monetary amounts that identify the total amount of the contract that needs to be paid from one party to another. - :param list[TerminationDates] termination_dates: (optional) The dates on + :param List[TerminationDates] termination_dates: (optional) The dates on which the document is to be terminated. - :param list[ContractTypes] contract_types: (optional) The contract type as + :param List[ContractTypes] contract_types: (optional) The contract type as declared in the document. - :param list[ContractTerms] contract_terms: (optional) The durations of the + :param List[ContractTerms] contract_terms: (optional) The durations of the contract. - :param list[PaymentTerms] payment_terms: (optional) The document's payment + :param List[PaymentTerms] payment_terms: (optional) The document's payment durations. - :param list[ContractCurrencies] contract_currencies: (optional) The + :param List[ContractCurrencies] contract_currencies: (optional) The contract currencies as declared in the document. - :param list[Tables] tables: (optional) Definition of tables identified in + :param List[Tables] tables: (optional) Definition of tables identified in the input document. :param DocStructure document_structure: (optional) The structure of the input document. - :param list[Parties] parties: (optional) Definitions of the parties + :param List[Parties] parties: (optional) Definitions of the parties identified in the input document. """ self.document = document @@ -1898,7 +2010,7 @@ def __init__(self, self.parties = parties @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifyReturn': """Initialize a ClassifyReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -1969,7 +2081,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifyReturn 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, 'document') and self.document is not None: @@ -2021,17 +2138,21 @@ def _to_dict(self): _dict['parties'] = [x._to_dict() for x in self.parties] return _dict - def __str__(self): + 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 ClassifyReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifyReturn') -> 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): + def __ne__(self, other: 'ClassifyReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2062,14 +2183,14 @@ class ColumnHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = 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: """ Initialize a ColumnHeaders object. @@ -2102,7 +2223,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ColumnHeaders': """Initialize a ColumnHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -2132,7 +2253,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ColumnHeaders 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, 'cell_id') and self.cell_id is not None: @@ -2158,17 +2284,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 ColumnHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ColumnHeaders') -> 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): + def __ne__(self, other: 'ColumnHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2182,21 +2312,21 @@ class CompareReturn(): `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :attr list[Document] documents: (optional) Information about the documents being + :attr List[Document] documents: (optional) Information about the documents being compared. - :attr list[AlignedElement] aligned_elements: (optional) A list of pairs of + :attr List[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. - :attr list[UnalignedElement] unaligned_elements: (optional) A list of elements + :attr List[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. """ def __init__(self, *, - model_id=None, - model_version=None, - documents=None, - aligned_elements=None, - unaligned_elements=None): + model_id: str = None, + model_version: str = None, + documents: List['Document'] = None, + aligned_elements: List['AlignedElement'] = None, + unaligned_elements: List['UnalignedElement'] = None) -> None: """ Initialize a CompareReturn object. @@ -2205,11 +2335,11 @@ def __init__(self, value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :param list[Document] documents: (optional) Information about the documents + :param List[Document] documents: (optional) Information about the documents being compared. - :param list[AlignedElement] aligned_elements: (optional) A list of pairs of + :param List[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. - :param list[UnalignedElement] unaligned_elements: (optional) A list of + :param List[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. """ self.model_id = model_id @@ -2219,7 +2349,7 @@ def __init__(self, self.unaligned_elements = unaligned_elements @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CompareReturn': """Initialize a CompareReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -2251,7 +2381,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CompareReturn 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, 'model_id') and self.model_id is not None: @@ -2273,17 +2408,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 CompareReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CompareReturn') -> 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): + def __ne__(self, other: 'CompareReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2296,7 +2435,7 @@ class Contact(): :attr str role: (optional) A string listing the role of the contact. """ - def __init__(self, *, name=None, role=None): + def __init__(self, *, name: str = None, role: str = None) -> None: """ Initialize a Contact object. @@ -2307,7 +2446,7 @@ def __init__(self, *, name=None, role=None): self.role = role @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Contact': """Initialize a Contact object from a json dictionary.""" args = {} valid_keys = ['name', 'role'] @@ -2322,7 +2461,12 @@ def _from_dict(cls, _dict): args['role'] = _dict.get('role') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Contact 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: @@ -2331,17 +2475,21 @@ def _to_dict(self): _dict['role'] = self.role return _dict - def __str__(self): + 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 Contact object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Contact') -> 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): + def __ne__(self, other: 'Contact') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2357,7 +2505,8 @@ class Contexts(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Contexts object. @@ -2370,7 +2519,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Contexts': """Initialize a Contexts object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -2385,7 +2534,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Contexts 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: @@ -2394,17 +2548,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Contexts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Contexts') -> 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): + def __ne__(self, other: 'Contexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2422,7 +2580,7 @@ class ContractAmts(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2431,12 +2589,12 @@ class ContractAmts(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractAmts object. @@ -2449,7 +2607,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2463,7 +2621,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractAmts': """Initialize a ContractAmts object from a json dictionary.""" args = {} valid_keys = [ @@ -2490,7 +2648,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractAmts 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, @@ -2509,17 +2672,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractAmts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractAmts') -> 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): + def __ne__(self, other: 'ContractAmts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2543,7 +2710,7 @@ class ContractCurrencies(): currency, which is listed as a string in [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2552,11 +2719,11 @@ class ContractCurrencies(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractCurrencies object. @@ -2567,7 +2734,7 @@ def __init__(self, currency, which is listed as a string in [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2580,7 +2747,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractCurrencies': """Initialize a ContractCurrencies object from a json dictionary.""" args = {} valid_keys = [ @@ -2604,7 +2771,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractCurrencies 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, @@ -2621,17 +2793,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractCurrencies object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractCurrencies') -> 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): + def __ne__(self, other: 'ContractCurrencies') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2657,7 +2833,7 @@ class ContractTerms(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2666,12 +2842,12 @@ class ContractTerms(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractTerms object. @@ -2684,7 +2860,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2698,7 +2874,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractTerms': """Initialize a ContractTerms object from a json dictionary.""" args = {} valid_keys = [ @@ -2725,7 +2901,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractTerms 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, @@ -2744,17 +2925,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractTerms object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractTerms') -> 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): + def __ne__(self, other: 'ContractTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2774,7 +2959,7 @@ class ContractTypes(): :attr str confidence_level: (optional) The confidence level in the identification of the contract type. :attr str text: (optional) The contract type. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2783,17 +2968,17 @@ class ContractTypes(): def __init__(self, *, - confidence_level=None, - text=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractTypes object. :param str confidence_level: (optional) The confidence level in the identification of the contract type. :param str text: (optional) The contract type. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2805,7 +2990,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractTypes': """Initialize a ContractTypes object from a json dictionary.""" args = {} valid_keys = ['confidence_level', 'text', 'provenance_ids', 'location'] @@ -2824,7 +3009,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractTypes 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, @@ -2838,17 +3028,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractTypes object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractTypes') -> 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): + def __ne__(self, other: 'ContractTypes') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2873,10 +3067,10 @@ class DocCounts(): def __init__(self, *, - total=None, - pending=None, - successful=None, - failed=None): + total: int = None, + pending: int = None, + successful: int = None, + failed: int = None) -> None: """ Initialize a DocCounts object. @@ -2893,7 +3087,7 @@ def __init__(self, self.failed = failed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocCounts': """Initialize a DocCounts object from a json dictionary.""" args = {} valid_keys = ['total', 'pending', 'successful', 'failed'] @@ -2912,7 +3106,12 @@ def _from_dict(cls, _dict): args['failed'] = _dict.get('failed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocCounts 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, 'total') and self.total is not None: @@ -2925,17 +3124,21 @@ def _to_dict(self): _dict['failed'] = self.failed return _dict - def __str__(self): + 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 DocCounts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocCounts') -> 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): + def __ne__(self, other: 'DocCounts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2950,7 +3153,8 @@ class DocInfo(): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, *, html=None, title=None, hash=None): + def __init__(self, *, html: str = None, title: str = None, + hash: str = None) -> None: """ Initialize a DocInfo object. @@ -2965,7 +3169,7 @@ def __init__(self, *, html=None, title=None, hash=None): self.hash = hash @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocInfo': """Initialize a DocInfo object from a json dictionary.""" args = {} valid_keys = ['html', 'title', 'hash'] @@ -2982,7 +3186,12 @@ def _from_dict(cls, _dict): args['hash'] = _dict.get('hash') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocInfo 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, 'html') and self.html is not None: @@ -2993,17 +3202,21 @@ def _to_dict(self): _dict['hash'] = self.hash return _dict - def __str__(self): + 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 DocInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocInfo') -> 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): + def __ne__(self, other: 'DocInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3012,31 +3225,31 @@ class DocStructure(): """ The structure of the input document. - :attr list[SectionTitles] section_titles: (optional) An array containing one + :attr List[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. - :attr list[LeadingSentence] leading_sentences: (optional) An array containing + :attr List[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. - :attr list[Paragraphs] paragraphs: (optional) An array containing one object per + :attr List[Paragraphs] paragraphs: (optional) An array containing one object per paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. """ def __init__(self, *, - section_titles=None, - leading_sentences=None, - paragraphs=None): + section_titles: List['SectionTitles'] = None, + leading_sentences: List['LeadingSentence'] = None, + paragraphs: List['Paragraphs'] = None) -> None: """ Initialize a DocStructure object. - :param list[SectionTitles] section_titles: (optional) An array containing + :param List[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. - :param list[LeadingSentence] leading_sentences: (optional) An array + :param List[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. - :param list[Paragraphs] paragraphs: (optional) An array containing one + :param List[Paragraphs] paragraphs: (optional) An array containing one object per paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. """ @@ -3045,7 +3258,7 @@ def __init__(self, self.paragraphs = paragraphs @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocStructure': """Initialize a DocStructure object from a json dictionary.""" args = {} valid_keys = ['section_titles', 'leading_sentences', 'paragraphs'] @@ -3070,7 +3283,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocStructure 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, 'section_titles') and self.section_titles is not None: @@ -3086,17 +3304,21 @@ def _to_dict(self): _dict['paragraphs'] = [x._to_dict() for x in self.paragraphs] return _dict - def __str__(self): + 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 DocStructure object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocStructure') -> 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): + def __ne__(self, other: 'DocStructure') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3113,7 +3335,12 @@ class Document(): only in the output of the **Comparing two documents** method. """ - def __init__(self, *, title=None, html=None, hash=None, label=None): + def __init__(self, + *, + title: str = None, + html: str = None, + hash: str = None, + label: str = None) -> None: """ Initialize a Document object. @@ -3130,7 +3357,7 @@ def __init__(self, *, title=None, html=None, hash=None, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Document': """Initialize a Document object from a json dictionary.""" args = {} valid_keys = ['title', 'html', 'hash', 'label'] @@ -3149,7 +3376,12 @@ def _from_dict(cls, _dict): args['label'] = _dict.get('label') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Document 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, 'title') and self.title is not None: @@ -3162,17 +3394,21 @@ def _to_dict(self): _dict['label'] = self.label return _dict - def __str__(self): + 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 Document object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Document') -> 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): + def __ne__(self, other: 'Document') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3187,7 +3423,7 @@ class EffectiveDates(): :attr str text_normalized: (optional) The normalized form of the effective date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -3196,11 +3432,11 @@ class EffectiveDates(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a EffectiveDates object. @@ -3210,7 +3446,7 @@ def __init__(self, :param str text_normalized: (optional) The normalized form of the effective date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -3223,7 +3459,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EffectiveDates': """Initialize a EffectiveDates object from a json dictionary.""" args = {} valid_keys = [ @@ -3247,7 +3483,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EffectiveDates 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, @@ -3264,17 +3505,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 EffectiveDates object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EffectiveDates') -> 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): + def __ne__(self, other: 'EffectiveDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3295,20 +3540,20 @@ class Element(): element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - location=None, - text=None, - types=None, - categories=None, - attributes=None): + location: 'Location' = None, + text: str = None, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a Element object. @@ -3316,12 +3561,12 @@ def __init__(self, element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.location = location self.text = text @@ -3330,7 +3575,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Element': """Initialize a Element object from a json dictionary.""" args = {} valid_keys = ['location', 'text', 'types', 'categories', 'attributes'] @@ -3357,7 +3602,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Element 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, 'location') and self.location is not None: @@ -3372,17 +3622,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 Element object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Element') -> 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): + def __ne__(self, other: 'Element') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3398,7 +3652,7 @@ class ElementLocations(): element in the input document. """ - def __init__(self, *, begin=None, end=None): + def __init__(self, *, begin: int = None, end: int = None) -> None: """ Initialize a ElementLocations object. @@ -3411,7 +3665,7 @@ def __init__(self, *, begin=None, end=None): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ElementLocations': """Initialize a ElementLocations object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -3426,7 +3680,12 @@ def _from_dict(cls, _dict): args['end'] = _dict.get('end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ElementLocations 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, 'begin') and self.begin is not None: @@ -3435,17 +3694,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 ElementLocations object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ElementLocations') -> 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): + def __ne__(self, other: 'ElementLocations') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3461,22 +3724,22 @@ class ElementPair(): :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr list[TypeLabelComparison] types: (optional) Description of the action + :attr List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional + :attr List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - document_label=None, - text=None, - location=None, - types=None, - categories=None, - attributes=None): + document_label: str = None, + text: str = None, + location: 'Location' = None, + types: List['TypeLabelComparison'] = None, + categories: List['CategoryComparison'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a ElementPair object. @@ -3487,12 +3750,12 @@ def __init__(self, :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :param list[TypeLabelComparison] types: (optional) Description of the + :param List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :param list[CategoryComparison] categories: (optional) List of functional + :param List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.text = text @@ -3502,7 +3765,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ElementPair': """Initialize a ElementPair object from a json dictionary.""" args = {} valid_keys = [ @@ -3535,7 +3798,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ElementPair 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, 'document_label') and self.document_label is not None: @@ -3552,17 +3820,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 ElementPair object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ElementPair') -> 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): + def __ne__(self, other: 'ElementPair') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3588,15 +3860,15 @@ class FeedbackDataInput(): """ def __init__(self, - feedback_type, - location, - text, - original_labels, - updated_labels, + feedback_type: str, + location: 'Location', + text: str, + original_labels: 'OriginalLabelsIn', + updated_labels: 'UpdatedLabelsIn', *, - document=None, - model_id=None, - model_version=None): + document: 'ShortDoc' = None, + model_id: str = None, + model_version: str = None) -> None: """ Initialize a FeedbackDataInput object. @@ -3626,7 +3898,7 @@ def __init__(self, self.updated_labels = updated_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': """Initialize a FeedbackDataInput object from a json dictionary.""" args = {} valid_keys = [ @@ -3678,9 +3950,14 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDataInput 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, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: @@ -3700,17 +3977,21 @@ def _to_dict(self): _dict['updated_labels'] = self.updated_labels._to_dict() return _dict - def __str__(self): + 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 FeedbackDataInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDataInput') -> 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): + def __ne__(self, other: 'FeedbackDataInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3740,15 +4021,15 @@ class FeedbackDataOutput(): def __init__(self, *, - feedback_type=None, - document=None, - model_id=None, - model_version=None, - location=None, - text=None, - original_labels=None, - updated_labels=None, - pagination=None): + feedback_type: str = None, + document: 'ShortDoc' = None, + model_id: str = None, + model_version: str = None, + location: 'Location' = None, + text: str = None, + original_labels: 'OriginalLabelsOut' = None, + updated_labels: 'UpdatedLabelsOut' = None, + pagination: 'Pagination' = None) -> None: """ Initialize a FeedbackDataOutput object. @@ -3782,7 +4063,7 @@ def __init__(self, self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDataOutput': """Initialize a FeedbackDataOutput object from a json dictionary.""" args = {} valid_keys = [ @@ -3817,7 +4098,12 @@ def _from_dict(cls, _dict): args['pagination'] = Pagination._from_dict(_dict.get('pagination')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDataOutput 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, 'feedback_type') and self.feedback_type is not None: @@ -3841,17 +4127,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 FeedbackDataOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDataOutput') -> 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): + def __ne__(self, other: 'FeedbackDataOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3864,7 +4154,7 @@ class FeedbackDeleted(): :attr str message: (optional) Status message returned from the service. """ - def __init__(self, *, status=None, message=None): + def __init__(self, *, status: int = None, message: str = None) -> None: """ Initialize a FeedbackDeleted object. @@ -3875,7 +4165,7 @@ def __init__(self, *, status=None, message=None): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDeleted': """Initialize a FeedbackDeleted object from a json dictionary.""" args = {} valid_keys = ['status', 'message'] @@ -3890,7 +4180,12 @@ def _from_dict(cls, _dict): args['message'] = _dict.get('message') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDeleted 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, 'status') and self.status is not None: @@ -3899,17 +4194,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 FeedbackDeleted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDeleted') -> 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): + def __ne__(self, other: 'FeedbackDeleted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3918,21 +4217,21 @@ class FeedbackList(): """ The results of a successful **List Feedback** request for all feedback. - :attr list[GetFeedback] feedback: (optional) A list of all feedback for the + :attr List[GetFeedback] feedback: (optional) A list of all feedback for the document. """ - def __init__(self, *, feedback=None): + def __init__(self, *, feedback: List['GetFeedback'] = None) -> None: """ Initialize a FeedbackList object. - :param list[GetFeedback] feedback: (optional) A list of all feedback for + :param List[GetFeedback] feedback: (optional) A list of all feedback for the document. """ self.feedback = feedback @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackList': """Initialize a FeedbackList object from a json dictionary.""" args = {} valid_keys = ['feedback'] @@ -3947,24 +4246,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackList 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, 'feedback') and self.feedback is not None: _dict['feedback'] = [x._to_dict() for x in self.feedback] return _dict - def __str__(self): + 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 FeedbackList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackList') -> 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): + def __ne__(self, other: 'FeedbackList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3986,11 +4294,11 @@ class FeedbackReturn(): def __init__(self, *, - feedback_id=None, - user_id=None, - comment=None, - created=None, - feedback_data=None): + feedback_id: str = None, + user_id: str = None, + comment: str = None, + created: datetime = None, + feedback_data: 'FeedbackDataOutput' = None) -> None: """ Initialize a FeedbackReturn object. @@ -4011,7 +4319,7 @@ def __init__(self, self.feedback_data = feedback_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackReturn': """Initialize a FeedbackReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -4035,7 +4343,12 @@ def _from_dict(cls, _dict): _dict.get('feedback_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackReturn 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, 'feedback_id') and self.feedback_id is not None: @@ -4050,17 +4363,21 @@ def _to_dict(self): _dict['feedback_data'] = self.feedback_data._to_dict() return _dict - def __str__(self): + 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 FeedbackReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackReturn') -> 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): + def __ne__(self, other: 'FeedbackReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4081,10 +4398,10 @@ class GetFeedback(): def __init__(self, *, - feedback_id=None, - created=None, - comment=None, - feedback_data=None): + feedback_id: str = None, + created: datetime = None, + comment: str = None, + feedback_data: 'FeedbackDataOutput' = None) -> None: """ Initialize a GetFeedback object. @@ -4103,7 +4420,7 @@ def __init__(self, self.feedback_data = feedback_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GetFeedback': """Initialize a GetFeedback object from a json dictionary.""" args = {} valid_keys = ['feedback_id', 'created', 'comment', 'feedback_data'] @@ -4123,7 +4440,12 @@ def _from_dict(cls, _dict): _dict.get('feedback_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GetFeedback 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, 'feedback_id') and self.feedback_id is not None: @@ -4136,17 +4458,21 @@ def _to_dict(self): _dict['feedback_data'] = self.feedback_data._to_dict() return _dict - def __str__(self): + 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 GetFeedback object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GetFeedback') -> 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): + def __ne__(self, other: 'GetFeedback') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4165,11 +4491,11 @@ class HTMLReturn(): def __init__(self, *, - num_pages=None, - author=None, - publication_date=None, - title=None, - html=None): + num_pages: str = None, + author: str = None, + publication_date: str = None, + title: str = None, + html: str = None) -> None: """ Initialize a HTMLReturn object. @@ -4189,7 +4515,7 @@ def __init__(self, self.html = html @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'HTMLReturn': """Initialize a HTMLReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -4212,7 +4538,12 @@ def _from_dict(cls, _dict): args['html'] = _dict.get('html') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a HTMLReturn 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, 'num_pages') and self.num_pages is not None: @@ -4228,17 +4559,21 @@ def _to_dict(self): _dict['html'] = self.html return _dict - def __str__(self): + 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 HTMLReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'HTMLReturn') -> 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): + def __ne__(self, other: 'HTMLReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4260,7 +4595,11 @@ class Interpretation(): contains the ambiguous symbol as-is. """ - def __init__(self, *, value=None, numeric_value=None, unit=None): + def __init__(self, + *, + value: str = None, + numeric_value: float = None, + unit: str = None) -> None: """ Initialize a Interpretation object. @@ -4281,7 +4620,7 @@ def __init__(self, *, value=None, numeric_value=None, unit=None): self.unit = unit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Interpretation': """Initialize a Interpretation object from a json dictionary.""" args = {} valid_keys = ['value', 'numeric_value', 'unit'] @@ -4298,7 +4637,12 @@ def _from_dict(cls, _dict): args['unit'] = _dict.get('unit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Interpretation 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, 'value') and self.value is not None: @@ -4309,17 +4653,21 @@ def _to_dict(self): _dict['unit'] = self.unit return _dict - def __str__(self): + 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 Interpretation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Interpretation') -> 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): + def __ne__(self, other: 'Interpretation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4336,7 +4684,11 @@ class Key(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'Location' = None, + text: str = None) -> None: """ Initialize a Key object. @@ -4352,7 +4704,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Key': """Initialize a Key object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4369,7 +4721,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Key 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, 'cell_id') and self.cell_id is not None: @@ -4380,17 +4737,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 Key object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Key') -> 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): + def __ne__(self, other: 'Key') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4400,21 +4761,22 @@ class KeyValuePair(): Key-value pairs detected across cell boundaries. :attr Key key: (optional) A key in a key-value pair. - :attr list[Value] value: (optional) A list of values in a key-value pair. + :attr List[Value] value: (optional) A list of values in a key-value pair. """ - def __init__(self, *, key=None, value=None): + def __init__(self, *, key: 'Key' = None, + value: List['Value'] = None) -> None: """ Initialize a KeyValuePair object. :param Key key: (optional) A key in a key-value pair. - :param list[Value] value: (optional) A list of values in a key-value pair. + :param List[Value] value: (optional) A list of values in a key-value pair. """ self.key = key self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeyValuePair': """Initialize a KeyValuePair object from a json dictionary.""" args = {} valid_keys = ['key', 'value'] @@ -4429,7 +4791,12 @@ def _from_dict(cls, _dict): args['value'] = [Value._from_dict(x) for x in (_dict.get('value'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeyValuePair 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, 'key') and self.key is not None: @@ -4438,17 +4805,21 @@ def _to_dict(self): _dict['value'] = [x._to_dict() for x in self.value] return _dict - def __str__(self): + 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 KeyValuePair object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeyValuePair') -> 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): + def __ne__(self, other: 'KeyValuePair') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4463,7 +4834,7 @@ class Label(): :attr str party: The identified `party` of the element. """ - def __init__(self, nature, party): + def __init__(self, nature: str, party: str) -> None: """ Initialize a Label object. @@ -4474,7 +4845,7 @@ def __init__(self, nature, party): self.party = party @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Label': """Initialize a Label object from a json dictionary.""" args = {} valid_keys = ['nature', 'party'] @@ -4495,7 +4866,12 @@ def _from_dict(cls, _dict): 'Required property \'party\' not present in Label JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Label 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, 'nature') and self.nature is not None: @@ -4504,17 +4880,21 @@ def _to_dict(self): _dict['party'] = self.party return _dict - def __str__(self): + 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 Label object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Label') -> 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): + def __ne__(self, other: 'Label') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4527,11 +4907,15 @@ class LeadingSentence(): :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr list[ElementLocations] element_locations: (optional) An array of + :attr List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ - def __init__(self, *, text=None, location=None, element_locations=None): + def __init__(self, + *, + text: str = None, + location: 'Location' = None, + element_locations: List['ElementLocations'] = None) -> None: """ Initialize a LeadingSentence object. @@ -4539,7 +4923,7 @@ def __init__(self, *, text=None, location=None, element_locations=None): :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :param list[ElementLocations] element_locations: (optional) An array of + :param List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ self.text = text @@ -4547,7 +4931,7 @@ def __init__(self, *, text=None, location=None, element_locations=None): self.element_locations = element_locations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LeadingSentence': """Initialize a LeadingSentence object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'element_locations'] @@ -4567,7 +4951,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LeadingSentence 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: @@ -4581,17 +4970,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 LeadingSentence object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LeadingSentence') -> 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): + def __ne__(self, other: 'LeadingSentence') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4605,7 +4998,7 @@ class Location(): :attr int end: The element's `end` index. """ - def __init__(self, begin, end): + def __init__(self, begin: int, end: int) -> None: """ Initialize a Location object. @@ -4616,7 +5009,7 @@ def __init__(self, begin, end): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -4637,7 +5030,12 @@ def _from_dict(cls, _dict): 'Required property \'end\' not present in Location JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Location 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, 'begin') and self.begin is not None: @@ -4646,17 +5044,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 Location object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Location') -> 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): + def __ne__(self, other: 'Location') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4671,7 +5073,8 @@ class Mention(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Mention object. @@ -4684,7 +5087,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -4699,7 +5102,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Mention 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: @@ -4708,17 +5116,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Mention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Mention') -> 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): + def __ne__(self, other: 'Mention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4727,26 +5139,27 @@ class OriginalLabelsIn(): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element + :attr List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :attr list[Category] categories: List of functional categories into which the + :attr List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ - def __init__(self, types, categories): + def __init__(self, types: List['TypeLabel'], + categories: List['Category']) -> None: """ Initialize a OriginalLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the + :param List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :param list[Category] categories: List of functional categories into which + :param List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OriginalLabelsIn': """Initialize a OriginalLabelsIn object from a json dictionary.""" args = {} valid_keys = ['types', 'categories'] @@ -4773,7 +5186,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OriginalLabelsIn 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, 'types') and self.types is not None: @@ -4782,17 +5200,21 @@ def _to_dict(self): _dict['categories'] = [x._to_dict() for x in self.categories] return _dict - def __str__(self): + 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 OriginalLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OriginalLabelsIn') -> 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): + def __ne__(self, other: 'OriginalLabelsIn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4801,22 +5223,26 @@ class OriginalLabelsOut(): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) A string identifying the type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ - def __init__(self, *, types=None, categories=None, modification=None): + def __init__(self, + *, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + modification: str = None) -> None: """ Initialize a OriginalLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) A string identifying the type of @@ -4828,7 +5254,7 @@ def __init__(self, *, types=None, categories=None, modification=None): self.modification = modification @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} valid_keys = ['types', 'categories', 'modification'] @@ -4849,7 +5275,12 @@ def _from_dict(cls, _dict): args['modification'] = _dict.get('modification') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OriginalLabelsOut 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, 'types') and self.types is not None: @@ -4860,17 +5291,21 @@ def _to_dict(self): _dict['modification'] = self.modification return _dict - def __str__(self): + 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 OriginalLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OriginalLabelsOut') -> 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): + def __ne__(self, other: 'OriginalLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4899,11 +5334,11 @@ class Pagination(): def __init__(self, *, - refresh_cursor=None, - next_cursor=None, - refresh_url=None, - next_url=None, - total=None): + refresh_cursor: str = None, + next_cursor: str = None, + refresh_url: str = None, + next_url: str = None, + total: int = None) -> None: """ Initialize a Pagination object. @@ -4924,7 +5359,7 @@ def __init__(self, self.total = total @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} valid_keys = [ @@ -4947,7 +5382,12 @@ def _from_dict(cls, _dict): args['total'] = _dict.get('total') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_cursor') and self.refresh_cursor is not None: @@ -4962,17 +5402,21 @@ def _to_dict(self): _dict['total'] = self.total return _dict - def __str__(self): + 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 Pagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pagination') -> 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): + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4986,7 +5430,7 @@ class Paragraphs(): `end`. """ - def __init__(self, *, location=None): + def __init__(self, *, location: 'Location' = None) -> None: """ Initialize a Paragraphs object. @@ -4997,7 +5441,7 @@ def __init__(self, *, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Paragraphs': """Initialize a Paragraphs object from a json dictionary.""" args = {} valid_keys = ['location'] @@ -5010,24 +5454,33 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Paragraphs 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, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Paragraphs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Paragraphs') -> 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): + def __ne__(self, other: 'Paragraphs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5041,22 +5494,22 @@ class Parties(): :attr str role: (optional) A string identifying the party's role. :attr str importance: (optional) A string that identifies the importance of the party. - :attr list[Address] addresses: (optional) A list of the party's address or + :attr List[Address] addresses: (optional) A list of the party's address or addresses. - :attr list[Contact] contacts: (optional) A list of the names and roles of + :attr List[Contact] contacts: (optional) A list of the names and roles of contacts identified in the input document. - :attr list[Mention] mentions: (optional) A list of the party's mentions in the + :attr List[Mention] mentions: (optional) A list of the party's mentions in the input document. """ def __init__(self, *, - party=None, - role=None, - importance=None, - addresses=None, - contacts=None, - mentions=None): + party: str = None, + role: str = None, + importance: str = None, + addresses: List['Address'] = None, + contacts: List['Contact'] = None, + mentions: List['Mention'] = None) -> None: """ Initialize a Parties object. @@ -5064,11 +5517,11 @@ def __init__(self, :param str role: (optional) A string identifying the party's role. :param str importance: (optional) A string that identifies the importance of the party. - :param list[Address] addresses: (optional) A list of the party's address or + :param List[Address] addresses: (optional) A list of the party's address or addresses. - :param list[Contact] contacts: (optional) A list of the names and roles of + :param List[Contact] contacts: (optional) A list of the names and roles of contacts identified in the input document. - :param list[Mention] mentions: (optional) A list of the party's mentions in + :param List[Mention] mentions: (optional) A list of the party's mentions in the input document. """ self.party = party @@ -5079,7 +5532,7 @@ def __init__(self, self.mentions = mentions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Parties': """Initialize a Parties object from a json dictionary.""" args = {} valid_keys = [ @@ -5110,7 +5563,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Parties 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, 'party') and self.party is not None: @@ -5127,17 +5585,21 @@ def _to_dict(self): _dict['mentions'] = [x._to_dict() for x in self.mentions] return _dict - def __str__(self): + 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 Parties object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Parties') -> 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): + def __ne__(self, other: 'Parties') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5162,7 +5624,7 @@ class PaymentTerms(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -5171,12 +5633,12 @@ class PaymentTerms(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a PaymentTerms object. @@ -5189,7 +5651,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -5203,7 +5665,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PaymentTerms': """Initialize a PaymentTerms object from a json dictionary.""" args = {} valid_keys = [ @@ -5230,7 +5692,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PaymentTerms 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, @@ -5249,17 +5716,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 PaymentTerms object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PaymentTerms') -> 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): + def __ne__(self, other: 'PaymentTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5298,14 +5769,14 @@ class RowHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: 'Location' = 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: """ Initialize a RowHeaders object. @@ -5338,7 +5809,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RowHeaders': """Initialize a RowHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5368,7 +5839,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RowHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5394,17 +5870,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 RowHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RowHeaders') -> 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): + def __ne__(self, other: 'RowHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5419,7 +5899,8 @@ class SectionTitle(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a SectionTitle object. @@ -5432,7 +5913,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SectionTitle': """Initialize a SectionTitle object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -5447,7 +5928,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SectionTitle 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: @@ -5456,17 +5942,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 SectionTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SectionTitle') -> 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): + def __ne__(self, other: 'SectionTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5485,16 +5975,16 @@ class SectionTitles(): :attr int level: (optional) An integer indicating the level at which the section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. - :attr list[ElementLocations] element_locations: (optional) An array of + :attr List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ def __init__(self, *, - text=None, - location=None, - level=None, - element_locations=None): + text: str = None, + location: 'Location' = None, + level: int = None, + element_locations: List['ElementLocations'] = None) -> None: """ Initialize a SectionTitles object. @@ -5506,7 +5996,7 @@ def __init__(self, section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. - :param list[ElementLocations] element_locations: (optional) An array of + :param List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ self.text = text @@ -5515,7 +6005,7 @@ def __init__(self, self.element_locations = element_locations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SectionTitles': """Initialize a SectionTitles object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'level', 'element_locations'] @@ -5537,7 +6027,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SectionTitles 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: @@ -5553,17 +6048,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 SectionTitles object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SectionTitles') -> 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): + def __ne__(self, other: 'SectionTitles') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5576,7 +6075,7 @@ class ShortDoc(): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, *, title=None, hash=None): + def __init__(self, *, title: str = None, hash: str = None) -> None: """ Initialize a ShortDoc object. @@ -5588,7 +6087,7 @@ def __init__(self, *, title=None, hash=None): self.hash = hash @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ShortDoc': """Initialize a ShortDoc object from a json dictionary.""" args = {} valid_keys = ['title', 'hash'] @@ -5603,7 +6102,12 @@ def _from_dict(cls, _dict): args['hash'] = _dict.get('hash') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ShortDoc 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, 'title') and self.title is not None: @@ -5612,17 +6116,21 @@ def _to_dict(self): _dict['hash'] = self.hash return _dict - def __str__(self): + 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 ShortDoc object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ShortDoc') -> 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): + def __ne__(self, other: 'ShortDoc') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5649,13 +6157,13 @@ class TableHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = 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: """ Initialize a TableHeaders object. @@ -5684,7 +6192,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5712,7 +6220,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5735,17 +6248,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableHeaders') -> 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): + def __ne__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5758,16 +6275,16 @@ class TableReturn(): :attr str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :attr str model_version: (optional) The version of the `tables` model ID. - :attr list[Tables] tables: (optional) Definitions of the tables identified in + :attr List[Tables] tables: (optional) Definitions of the tables identified in the input document. """ def __init__(self, *, - document=None, - model_id=None, - model_version=None, - tables=None): + document: 'DocInfo' = None, + model_id: str = None, + model_version: str = None, + tables: List['Tables'] = None) -> None: """ Initialize a TableReturn object. @@ -5776,7 +6293,7 @@ def __init__(self, :param str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :param str model_version: (optional) The version of the `tables` model ID. - :param list[Tables] tables: (optional) Definitions of the tables identified + :param List[Tables] tables: (optional) Definitions of the tables identified in the input document. """ self.document = document @@ -5785,7 +6302,7 @@ def __init__(self, self.tables = tables @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableReturn': """Initialize a TableReturn object from a json dictionary.""" args = {} valid_keys = ['document', 'model_id', 'model_version', 'tables'] @@ -5806,7 +6323,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableReturn 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, 'document') and self.document is not None: @@ -5819,17 +6341,21 @@ def _to_dict(self): _dict['tables'] = [x._to_dict() for x in self.tables] return _dict - def __str__(self): + 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 TableReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableReturn') -> 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): + def __ne__(self, other: 'TableReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5846,7 +6372,8 @@ class TableTitle(): :attr str text: (optional) The text of the identified table title or caption. """ - def __init__(self, *, location=None, text=None): + def __init__(self, *, location: 'Location' = None, + text: str = None) -> None: """ Initialize a TableTitle object. @@ -5860,7 +6387,7 @@ def __init__(self, *, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableTitle': """Initialize a TableTitle object from a json dictionary.""" args = {} valid_keys = ['location', 'text'] @@ -5875,7 +6402,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableTitle 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, 'location') and self.location is not None: @@ -5884,17 +6416,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableTitle') -> 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): + def __ne__(self, other: 'TableTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5914,36 +6450,36 @@ class Tables(): current table of the form `Table x.: ...`. Empty when no title is identified. When exposed, the `title` is also excluded from the `contexts` array of the same table. - :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + :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[RowHeaders] row_headers: (optional) An array of row-level cells, each + :attr List[RowHeaders] 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[ColumnHeaders] column_headers: (optional) An array of column-level + :attr List[ColumnHeaders] 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[BodyCells] body_cells: (optional) An array of cells that are neither + :attr List[BodyCells] 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[Contexts] contexts: (optional) An array of objects that list text + :attr List[Contexts] contexts: (optional) An array of objects that list text that is related to the table contents and that precedes or follows the current table. - :attr list[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs + :attr List[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs identified in the current table. """ def __init__(self, *, - location=None, - text=None, - section_title=None, - title=None, - table_headers=None, - row_headers=None, - column_headers=None, - body_cells=None, - contexts=None, - key_value_pairs=None): + location: 'Location' = None, + text: str = None, + section_title: 'SectionTitle' = None, + title: 'TableTitle' = None, + table_headers: List['TableHeaders'] = None, + row_headers: List['RowHeaders'] = None, + column_headers: List['ColumnHeaders'] = None, + body_cells: List['BodyCells'] = None, + contexts: List['Contexts'] = None, + key_value_pairs: List['KeyValuePair'] = None) -> None: """ Initialize a Tables object. @@ -5958,21 +6494,21 @@ def __init__(self, the current table of the form `Table x.: ...`. Empty when no title is identified. When exposed, the `title` is also excluded from the `contexts` array of the same table. - :param list[TableHeaders] table_headers: (optional) An array of table-level + :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[RowHeaders] row_headers: (optional) An array of row-level + :param List[RowHeaders] 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[ColumnHeaders] column_headers: (optional) An array of + :param List[ColumnHeaders] 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. - :param list[BodyCells] body_cells: (optional) An array of cells that are + :param List[BodyCells] 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. - :param list[Contexts] contexts: (optional) An array of objects that list + :param List[Contexts] contexts: (optional) An array of objects that list text that is related to the table contents and that precedes or follows the current table. - :param list[KeyValuePair] key_value_pairs: (optional) An array of key-value + :param List[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs identified in the current table. """ self.location = location @@ -5987,7 +6523,7 @@ def __init__(self, self.key_value_pairs = key_value_pairs @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Tables': """Initialize a Tables object from a json dictionary.""" args = {} valid_keys = [ @@ -6037,7 +6573,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Tables 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, 'location') and self.location is not None: @@ -6067,17 +6608,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 Tables object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Tables') -> 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): + def __ne__(self, other: 'Tables') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6092,7 +6637,7 @@ class TerminationDates(): :attr str text_normalized: (optional) The normalized form of the termination date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -6101,11 +6646,11 @@ class TerminationDates(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a TerminationDates object. @@ -6115,7 +6660,7 @@ def __init__(self, :param str text_normalized: (optional) The normalized form of the termination date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -6128,7 +6673,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TerminationDates': """Initialize a TerminationDates object from a json dictionary.""" args = {} valid_keys = [ @@ -6152,7 +6697,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TerminationDates 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, @@ -6169,17 +6719,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TerminationDates object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TerminationDates') -> 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): + def __ne__(self, other: 'TerminationDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6199,25 +6753,28 @@ class TypeLabel(): :attr Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ - def __init__(self, *, label=None, provenance_ids=None): + def __init__(self, + *, + label: 'Label' = None, + provenance_ids: List[str] = None) -> None: """ Initialize a TypeLabel object. :param Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TypeLabel': """Initialize a TypeLabel object from a json dictionary.""" args = {} valid_keys = ['label', 'provenance_ids'] @@ -6232,7 +6789,12 @@ def _from_dict(cls, _dict): args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TypeLabel 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, 'label') and self.label is not None: @@ -6241,17 +6803,21 @@ def _to_dict(self): _dict['provenance_ids'] = self.provenance_ids return _dict - def __str__(self): + 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 TypeLabel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TypeLabel') -> 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): + def __ne__(self, other: 'TypeLabel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6265,7 +6831,7 @@ class TypeLabelComparison(): and the `party` object identifies the affected party. """ - def __init__(self, *, label=None): + def __init__(self, *, label: 'Label' = None) -> None: """ Initialize a TypeLabelComparison object. @@ -6276,7 +6842,7 @@ def __init__(self, *, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TypeLabelComparison': """Initialize a TypeLabelComparison object from a json dictionary.""" args = {} valid_keys = ['label'] @@ -6289,24 +6855,33 @@ def _from_dict(cls, _dict): args['label'] = Label._from_dict(_dict.get('label')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TypeLabelComparison 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, 'label') and self.label is not None: _dict['label'] = self.label._to_dict() return _dict - def __str__(self): + 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 TypeLabelComparison object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TypeLabelComparison') -> 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): + def __ne__(self, other: 'TypeLabelComparison') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6322,22 +6897,22 @@ class UnalignedElement(): element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabelComparison] types: (optional) Description of the action + :attr List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional + :attr List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - document_label=None, - location=None, - text=None, - types=None, - categories=None, - attributes=None): + document_label: str = None, + location: 'Location' = None, + text: str = None, + types: List['TypeLabelComparison'] = None, + categories: List['CategoryComparison'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a UnalignedElement object. @@ -6348,12 +6923,12 @@ def __init__(self, element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. - :param list[TypeLabelComparison] types: (optional) Description of the + :param List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :param list[CategoryComparison] categories: (optional) List of functional + :param List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.location = location @@ -6363,7 +6938,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UnalignedElement': """Initialize a UnalignedElement object from a json dictionary.""" args = {} valid_keys = [ @@ -6396,7 +6971,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UnalignedElement 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, 'document_label') and self.document_label is not None: @@ -6413,17 +6993,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 UnalignedElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UnalignedElement') -> 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): + def __ne__(self, other: 'UnalignedElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6432,26 +7016,27 @@ class UpdatedLabelsIn(): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element + :attr List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :attr list[Category] categories: List of functional categories into which the + :attr List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ - def __init__(self, types, categories): + def __init__(self, types: List['TypeLabel'], + categories: List['Category']) -> None: """ Initialize a UpdatedLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the + :param List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :param list[Category] categories: List of functional categories into which + :param List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsIn': """Initialize a UpdatedLabelsIn object from a json dictionary.""" args = {} valid_keys = ['types', 'categories'] @@ -6478,7 +7063,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdatedLabelsIn 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, 'types') and self.types is not None: @@ -6487,17 +7077,21 @@ def _to_dict(self): _dict['categories'] = [x._to_dict() for x in self.categories] return _dict - def __str__(self): + 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 UpdatedLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UpdatedLabelsIn') -> 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): + def __ne__(self, other: 'UpdatedLabelsIn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6506,22 +7100,26 @@ class UpdatedLabelsOut(): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) The type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ - def __init__(self, *, types=None, categories=None, modification=None): + def __init__(self, + *, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + modification: str = None) -> None: """ Initialize a UpdatedLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) The type of modification the feedback @@ -6533,7 +7131,7 @@ def __init__(self, *, types=None, categories=None, modification=None): self.modification = modification @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} valid_keys = ['types', 'categories', 'modification'] @@ -6554,7 +7152,12 @@ def _from_dict(cls, _dict): args['modification'] = _dict.get('modification') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdatedLabelsOut 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, 'types') and self.types is not None: @@ -6565,17 +7168,21 @@ def _to_dict(self): _dict['modification'] = self.modification return _dict - def __str__(self): + 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 UpdatedLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UpdatedLabelsOut') -> 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): + def __ne__(self, other: 'UpdatedLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6601,7 +7208,11 @@ class Value(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'Location' = None, + text: str = None) -> None: """ Initialize a Value object. @@ -6617,7 +7228,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -6634,7 +7245,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Value 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, 'cell_id') and self.cell_id is not None: @@ -6645,16 +7261,20 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 Value object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Value') -> 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): + def __ne__(self, other: 'Value') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 640573678..0100cabe8 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,577 +1,1045 @@ -# coding: utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import os -import time -import jwt -from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -base_url = "https://gateway.watsonplatform.net/compare-comply/api" -feedback = { - "comment": "test commment", - "user_id": "wonder woman", - "feedback_id": "lala", - "feedback_data": { - "model_id": "contracts", - "original_labels": { - "categories": [ - { - "modification": "unchanged", - "provenance_ids": [], - "label": "Responsibilities" - }, - { - "modification": "removed", - "provenance_ids": [], - "label": "Amendments" - } - ], - "types": [ - { - "modification": "unchanged", - "provenance_ids": [ - "111", - "2222" - ], - "label": { - "party": "IBM", - "nature": "Obligation" - } - }, - { - "modification": "removed", - "provenance_ids": [ - "111", - "2222" - ], - "label": { - "party": "Exclusion", - "nature": "End User" - } - } - ] - }, - "text": "1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.", - "feedback_type": "element_classification", - "updated_labels": { - "categories": [ - { - "modification": "unchanged", - "label": "Responsibilities" - }, - { - "modification": "added", - "label": "Audits" - } - ], - "types": [ - { - "modification": "unchanged", - "label": { - "party": "IBM", - "nature": "Obligation" - } - }, - { - "modification": "added", - "label": { - "party": "Buyer", - "nature": "Disclaimer" - } - } - ] - }, - "model_version": "11.00", - "location": { - "begin": "214", - "end": "237" - }, - "document": { - "hash": "", - "title": "doc title" - } - }, - "created": "2018-11-16T22:57:14+0000" -} - - -batch = { - "function": "html_conversion", - "status": "completed", - "updated": "2018-11-12T21:02:43.867+0000", - "document_counts": { - "successful": 4, - "failed": 0, - "total": 4, - "pending": 0 - }, - "created": "2018-11-12T21:02:38.907+0000", - "input_bucket_location": "us-south", - "input_bucket_name": "compare-comply-integration-test-bucket-input", - "batch_id": "xxx", - "output_bucket_name": "compare-comply-integration-test-bucket-output", - "model": "contracts", - "output_bucket_location": "us-south" -} - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestCompareComplyV1(TestCase): - - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add( - responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @responses.activate - def test_convert_to_html(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/html_conversion') - - response = { - "hash": "0d9589556c16fca21c64ce9c8b10d065", - "html": "", - "num_pages": "4", - "publication_date": "2018-11-10", - "title": "Microsoft Word - contract_A.doc" - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file: - service.convert_to_html( - file, - model_id="contracts", - file_content_type="application/octet-stream") - - assert len(responses.calls) == 2 - - @responses.activate - def test_classify_elements(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/element_classification') - - response = [{ - "text": - "__November 9, 2018______________ date", - "categories": [], - "location": { - "begin": 19373, - "end": 19410 - }, - "types": [], - "attributes": [{ - "text": "November 9, 2018", - "type": "DateTime", - "location": { - "begin": 19375, - "end": 19391 - } - }] - }] - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file: - service.classify_elements( - file, - model_id="contracts", - file_content_type="application/octet-stream") - - assert len(responses.calls) == 2 - - @responses.activate - def test_extract_tables(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/tables') - - response = { - "model_version": - "0.2.8-SNAPSHOT", - "model_id": - "tables", - "document": { - "hash": "0906a4721a59ffeaf2ec12997aa4f7f7", - "title": "Design and build accessible PDF tables, sample tables" - }, - "tables": [{ - "section_title": { - "text": "Sample tables ", - "location": { - "begin": 2099, - "end": 2113 - } - }, - "text": - "Column header (TH) Column header (TH) Column header (TH) Row header (TH) Data cell (TD) Data cell (TD) Row header(TH) Data cell (TD) Data cell (TD) ", - "table_headers": [], - "row_headers": [], - "location": { - "begin": 2832, - "end": 4801 - }, - "body_cells": [], - }] - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/sample-tables.pdf'), 'rb') as file: - service.extract_tables(file) - - assert len(responses.calls) == 2 - - @responses.activate - def test_compare_documents(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/comparison') - - response = { - "aligned_elements": [ - { - "element_pair": [{ - "text": - "WITNESSETH: that the Owner and Contractor undertake and agree as follows:", - "types": [], - "document_label": - "file_1", - "attributes": [], - "categories": [], - "location": { - "begin": 3845, - "end": 4085 - } - }, { - "text": - "WITNESSETH: that the Owner and Contractor undertake and agree as follows:", - "types": [], - "document_label": - "file_2", - "attributes": [], - "categories": [], - "location": { - "begin": 3846, - "end": 4086 - } - }], - "provenance_ids": - ["1mSG/96z1wY4De35LAExJzhCo2t0DfvbYnTl+vbavjY="], - }, - ], - "model_id": - "contracts", - "model_version": - "1.0.0" - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file1: - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_B.pdf'), 'rb') as file2: - service.compare_documents(file1, file2) - - assert len(responses.calls) == 2 - - @responses.activate - def test_add_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback') - - feedback_data = { - "feedback_type": "element_classification", - "document": { - "hash": "", - "title": "doc title" - }, - "model_id": "contracts", - "model_version": "11.00", - "location": { - "begin": "214", - "end": "237" - }, - "text": "1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.", - "original_labels": { - "types": [ - { - "label": { - "nature": "Obligation", - "party": "IBM" - }, - "provenance_ids": [ - "85f5981a-ba91-44f5-9efa-0bd22e64b7bc", - "ce0480a1-5ef1-4c3e-9861-3743b5610795" - ] - }, - { - "label": { - "nature": "End User", - "party": "Exclusion" - }, - "provenance_ids": [ - "85f5981a-ba91-44f5-9efa-0bd22e64b7bc", - "ce0480a1-5ef1-4c3e-9861-3743b5610795" - ] - } - ], - "categories": [ - { - "label": "Responsibilities", - "provenance_ids": [] - }, - { - "label": "Amendments", - "provenance_ids": [] - } - ] - }, - "updated_labels": { - "types": [ - { - "label": { - "nature": "Obligation", - "party": "IBM" - } - }, - { - "label": { - "nature": "Disclaimer", - "party": "Buyer" - } - } - ], - "categories": [ - { - "label": "Responsibilities" - }, - { - "label": "Audits" - } - ] - } - } - - responses.add( - responses.POST, - url, - body=json.dumps(feedback), - status=200, - content_type='application/json') - - result = service.add_feedback( - feedback_data, - user_id="wonder woman", - comment="test commment").get_result() - assert result["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_get_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback/xxx') - - responses.add( - responses.GET, - url, - body=json.dumps(feedback), - status=200, - content_type='application/json') - - result = service.get_feedback("xxx").get_result() - assert result["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_list_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback') - - responses.add( - responses.GET, - url, - body=json.dumps({"feedback":[feedback]}), - status=200, - content_type='application/json') - - result = service.list_feedback().get_result() - assert result["feedback"][0]["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_delete_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback/xxx') - - response = { - "status": 200, - "message": "Successfully deleted the feedback with id - 90ae2cb9-e6c5-43eb-a70f-199959f76019" - } - - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - result = service.delete_feedback("xxx").get_result() - assert result["status"] == 200 - - assert len(responses.calls) == 2 - - @responses.activate - def test_create_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches') +import pytest +import responses +import tempfile +import ibm_watson.compare_comply_v1 +from ibm_watson.compare_comply_v1 import * - responses.add( - responses.POST, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') +base_url = 'https://gateway.watsonplatform.net/compare-comply/api' - with open(os.path.join(os.path.dirname(__file__), - '../../resources/dummy-storage-credentials.json'), 'rb') as input_credentials_file: - with open(os.path.join(os.path.dirname(__file__), - '../../resources/dummy-storage-credentials.json'), 'rb') as output_credentials_file: - result = service.create_batch( - "html_conversion", - input_credentials_file, - "us-south", - "compare-comply-integration-test-bucket-input", - output_credentials_file, - "us-south", - "compare-comply-integration-test-bucket-output").get_result() +############################################################################## +# Start of Service: HTMLConversion +############################################################################## +# region - assert result["batch_id"] == "xxx" - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for convert_to_html +#----------------------------------------------------------------------------- +class TestConvertToHtml(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches/xxx') - - responses.add( - responses.GET, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') - - result = service.get_batch("xxx").get_result() - assert result["batch_id"] == "xxx" - - assert len(responses.calls) == 2 - + def test_convert_to_html_response(self): + body = self.construct_full_body() + response = fake_response_HTMLReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_batches(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches') - - responses.add( - responses.GET, - url, - body=json.dumps({"batches": [batch]}), - status=200, - content_type='application/json') - - result = service.list_batches().get_result() - assert result["batches"][0]["batch_id"] == "xxx" - - assert len(responses.calls) == 2 - + def test_convert_to_html_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_HTMLReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_update_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches/xxx') - - responses.add( - responses.PUT, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') - - result = service.update_batch("xxx", "rescan").get_result() - assert result["batch_id"] == "xxx" - assert len(responses.calls) == 2 + def test_convert_to_html_empty(self): + check_empty_required_params(self, fake_response_HTMLReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/html_conversion' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.convert_to_html(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: HTMLConversion +############################################################################## + +############################################################################## +# Start of Service: ElementClassification +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for classify_elements +#----------------------------------------------------------------------------- +class TestClassifyElements(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_elements_response(self): + body = self.construct_full_body() + response = fake_response_ClassifyReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_elements_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifyReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_elements_empty(self): + check_empty_required_params(self, fake_response_ClassifyReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/element_classification' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.classify_elements(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: ElementClassification +############################################################################## + +############################################################################## +# Start of Service: Tables +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for extract_tables +#----------------------------------------------------------------------------- +class TestExtractTables(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_extract_tables_response(self): + body = self.construct_full_body() + response = fake_response_TableReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_extract_tables_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TableReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_extract_tables_empty(self): + check_empty_required_params(self, fake_response_TableReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/tables' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.extract_tables(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Tables +############################################################################## + +############################################################################## +# Start of Service: Comparison +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for compare_documents +#----------------------------------------------------------------------------- +class TestCompareDocuments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_compare_documents_response(self): + body = self.construct_full_body() + response = fake_response_CompareReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_compare_documents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CompareReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_compare_documents_empty(self): + check_empty_required_params(self, fake_response_CompareReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/comparison' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.compare_documents(**body) + return output + + def construct_full_body(self): + body = dict() + body['file_1'] = tempfile.NamedTemporaryFile() + body['file_2'] = tempfile.NamedTemporaryFile() + body['file_1_content_type'] = "string1" + body['file_2_content_type'] = "string1" + body['file_1_label'] = "string1" + body['file_2_label'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file_1'] = tempfile.NamedTemporaryFile() + body['file_2'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Comparison +############################################################################## + +############################################################################## +# Start of Service: Feedback +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for add_feedback +#----------------------------------------------------------------------------- +class TestAddFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_feedback_empty(self): + check_empty_required_params(self, fake_response_FeedbackReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.add_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_feedback +#----------------------------------------------------------------------------- +class TestListFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_feedback_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.list_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_type'] = "string1" + body['before'] = datetime.now().date() + body['after'] = datetime.now().date() + body['document_title'] = "string1" + body['model_id'] = "string1" + body['model_version'] = "string1" + body['category_removed'] = "string1" + body['category_added'] = "string1" + body['category_not_changed'] = "string1" + body['type_removed'] = "string1" + body['type_added'] = "string1" + body['type_not_changed'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + body['sort'] = "string1" + body['include_total'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_feedback +#----------------------------------------------------------------------------- +class TestGetFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_feedback_response(self): + body = self.construct_full_body() + response = fake_response_GetFeedback_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GetFeedback_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_feedback_empty(self): + check_empty_required_params(self, fake_response_GetFeedback_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback/{0}'.format(body['feedback_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.get_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_id'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['feedback_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_feedback +#----------------------------------------------------------------------------- +class TestDeleteFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackDeleted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackDeleted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_feedback_empty(self): + check_empty_required_params(self, fake_response_FeedbackDeleted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback/{0}'.format(body['feedback_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.delete_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_id'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['feedback_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Feedback +############################################################################## + +############################################################################## +# Start of Service: Batches +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_batch +#----------------------------------------------------------------------------- +class TestCreateBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.create_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['function'] = "string1" + body['input_credentials_file'] = tempfile.NamedTemporaryFile() + body['input_bucket_location'] = "string1" + body['input_bucket_name'] = "string1" + body['output_credentials_file'] = tempfile.NamedTemporaryFile() + body['output_bucket_location'] = "string1" + body['output_bucket_name'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['function'] = "string1" + body['input_credentials_file'] = tempfile.NamedTemporaryFile() + body['input_bucket_location'] = "string1" + body['input_bucket_name'] = "string1" + body['output_credentials_file'] = tempfile.NamedTemporaryFile() + body['output_bucket_location'] = "string1" + body['output_bucket_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_batches +#----------------------------------------------------------------------------- +class TestListBatches(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_batches_response(self): + body = self.construct_full_body() + response = fake_response_Batches_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_batches_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Batches_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_batches_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.list_batches(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_batch +#----------------------------------------------------------------------------- +class TestGetBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches/{0}'.format(body['batch_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.get_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['batch_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['batch_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_batch +#----------------------------------------------------------------------------- +class TestUpdateBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches/{0}'.format(body['batch_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.update_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['batch_id'] = "string1" + body['action'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['batch_id'] = "string1" + body['action'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Batches +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_HTMLReturn_json = """{"num_pages": "fake_num_pages", "author": "fake_author", "publication_date": "fake_publication_date", "title": "fake_title", "html": "fake_html"}""" +fake_response_ClassifyReturn_json = """{"document": {"title": "fake_title", "html": "fake_html", "hash": "fake_hash", "label": "fake_label"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "elements": [], "effective_dates": [], "contract_amounts": [], "termination_dates": [], "contract_types": [], "contract_terms": [], "payment_terms": [], "contract_currencies": [], "tables": [], "document_structure": {"section_titles": [], "leading_sentences": [], "paragraphs": []}, "parties": []}""" +fake_response_TableReturn_json = """{"document": {"html": "fake_html", "title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "tables": []}""" +fake_response_CompareReturn_json = """{"model_id": "fake_model_id", "model_version": "fake_model_version", "documents": [], "aligned_elements": [], "unaligned_elements": []}""" +fake_response_FeedbackReturn_json = """{"feedback_id": "fake_feedback_id", "user_id": "fake_user_id", "comment": "fake_comment", "created": "2017-05-16T13:56:54.957Z", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_FeedbackList_json = """{"feedback": []}""" +fake_response_GetFeedback_json = """{"feedback_id": "fake_feedback_id", "created": "2017-05-16T13:56:54.957Z", "comment": "fake_comment", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_FeedbackDeleted_json = """{"status": 6, "message": "fake_message"}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Batches_json = """{"batches": []}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" From 2146c308b8ccd5d5e051da0b5fdc4b7dfc650e23 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 14:58:05 -0500 Subject: [PATCH 06/28] refactor(discoveryv1): regenerate discovery v1 with tests --- ibm_watson/discovery_v1.py | 5213 +++++++++++++++++----------- test/unit/test_discovery_v1.py | 5844 +++++++++++++++++++++++++------- 2 files changed, 7903 insertions(+), 3154 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index eac3e348e..f57693456 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,22 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import date +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO +import sys ############################################################################## # Service @@ -38,13 +47,15 @@ class DiscoveryV1(BaseService): """The Discovery V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_NAME = 'discovery' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Discovery service. @@ -63,31 +74,25 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('discovery') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('discovery') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Environments ######################### - def create_environment(self, name, *, description=None, size=None, - **kwargs): + def create_environment(self, + name: str, + *, + description: str = None, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Create an environment. @@ -112,7 +117,9 @@ def create_environment(self, name, *, description=None, size=None, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -124,12 +131,13 @@ def create_environment(self, name, *, description=None, size=None, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_environments(self, *, name=None, **kwargs): + def list_environments(self, *, name: str = None, + **kwargs) -> 'DetailedResponse': """ List environments. @@ -144,7 +152,9 @@ def list_environments(self, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version, 'name': name} @@ -153,12 +163,13 @@ def list_environments(self, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_environment(self, environment_id, **kwargs): + def get_environment(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ Get environment info. @@ -174,7 +185,9 @@ def get_environment(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -184,18 +197,18 @@ def get_environment(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_environment(self, - environment_id, + environment_id: str, *, - name=None, - description=None, - size=None, - **kwargs): + name: str = None, + description: str = None, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Update an environment. @@ -219,7 +232,9 @@ def update_environment(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -232,12 +247,13 @@ def update_environment(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_environment(self, environment_id, **kwargs): + def delete_environment(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ Delete environment. @@ -253,7 +269,9 @@ def delete_environment(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -263,12 +281,13 @@ def delete_environment(self, environment_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_fields(self, environment_id, collection_ids, **kwargs): + def list_fields(self, environment_id: str, collection_ids: List[str], + **kwargs) -> 'DetailedResponse': """ List fields across collections. @@ -276,7 +295,7 @@ def list_fields(self, environment_id, collection_ids, **kwargs): specified collections. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs + :param List[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -291,7 +310,9 @@ def list_fields(self, environment_id, collection_ids, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = { @@ -304,8 +325,8 @@ def list_fields(self, environment_id, collection_ids, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -313,16 +334,17 @@ def list_fields(self, environment_id, collection_ids, **kwargs): # Configurations ######################### - def create_configuration(self, - environment_id, - name, - *, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None, - **kwargs): + 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': """ Add configuration. @@ -342,9 +364,9 @@ def create_configuration(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :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. @@ -371,7 +393,9 @@ def create_configuration(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -391,12 +415,16 @@ def create_configuration(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_configurations(self, environment_id, *, name=None, **kwargs): + def list_configurations(self, + environment_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': """ List configurations. @@ -415,7 +443,9 @@ def list_configurations(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version, 'name': name} @@ -425,12 +455,13 @@ def list_configurations(self, environment_id, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_configuration(self, environment_id, configuration_id, **kwargs): + def get_configuration(self, environment_id: str, configuration_id: str, + **kwargs) -> 'DetailedResponse': """ Get configuration details. @@ -449,7 +480,9 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -459,22 +492,23 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def update_configuration(self, - environment_id, - configuration_id, - name, - *, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None, - **kwargs): + 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': """ Update a configuration. @@ -494,9 +528,9 @@ def update_configuration(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :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. @@ -525,7 +559,9 @@ def update_configuration(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -545,12 +581,13 @@ def update_configuration(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_configuration(self, environment_id, configuration_id, **kwargs): + def delete_configuration(self, environment_id: str, configuration_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a configuration. @@ -576,7 +613,9 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -586,8 +625,8 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -596,13 +635,13 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): ######################### def create_collection(self, - environment_id, - name, + environment_id: str, + name: str, *, - description=None, - configuration_id=None, - language=None, - **kwargs): + description: str = None, + configuration_id: str = None, + language: str = None, + **kwargs) -> 'DetailedResponse': """ Create a collection. @@ -626,7 +665,9 @@ def create_collection(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -644,12 +685,16 @@ def create_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_collections(self, environment_id, *, name=None, **kwargs): + def list_collections(self, + environment_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': """ List collections. @@ -668,7 +713,9 @@ def list_collections(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version, 'name': name} @@ -678,12 +725,13 @@ def list_collections(self, environment_id, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_collection(self, environment_id, collection_id, **kwargs): + def get_collection(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get collection details. @@ -702,7 +750,9 @@ def get_collection(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -712,19 +762,19 @@ def get_collection(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_collection(self, - environment_id, - collection_id, - name, + environment_id: str, + collection_id: str, + name: str, *, - description=None, - configuration_id=None, - **kwargs): + description: str = None, + configuration_id: str = None, + **kwargs) -> 'DetailedResponse': """ Update a collection. @@ -743,11 +793,15 @@ def update_collection(self, raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') + if name is None: + raise ValueError('name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -764,12 +818,13 @@ def update_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_collection(self, environment_id, collection_id, **kwargs): + def delete_collection(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a collection. @@ -788,7 +843,9 @@ def delete_collection(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -798,12 +855,13 @@ def delete_collection(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_collection_fields(self, environment_id, collection_id, **kwargs): + def list_collection_fields(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ List collection fields. @@ -824,8 +882,9 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -835,8 +894,8 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -844,7 +903,8 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): # Query modifications ######################### - def list_expansions(self, environment_id, collection_id, **kwargs): + def list_expansions(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get the expansion list. @@ -866,7 +926,9 @@ def list_expansions(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -876,13 +938,14 @@ def list_expansions(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_expansions(self, environment_id, collection_id, expansions, - **kwargs): + def create_expansions(self, environment_id: str, collection_id: str, + expansions: List['Expansion'], + **kwargs) -> 'DetailedResponse': """ Create or update expansion list. @@ -892,7 +955,7 @@ def create_expansions(self, environment_id, collection_id, expansions, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param 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 @@ -921,7 +984,9 @@ def create_expansions(self, environment_id, collection_id, expansions, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -934,12 +999,13 @@ def create_expansions(self, environment_id, collection_id, expansions, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_expansions(self, environment_id, collection_id, **kwargs): + def delete_expansions(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete the expansion list. @@ -961,7 +1027,9 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -971,13 +1039,14 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_tokenization_dictionary_status(self, environment_id, collection_id, - **kwargs): + def get_tokenization_dictionary_status(self, environment_id: str, + collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get tokenization dictionary status. @@ -999,8 +1068,10 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_tokenization_dictionary_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_tokenization_dictionary_status') headers.update(sdk_headers) params = {'version': self.version} @@ -1010,17 +1081,18 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_tokenization_dictionary(self, - environment_id, - collection_id, - *, - tokenization_rules=None, - **kwargs): + def create_tokenization_dictionary( + self, + environment_id: str, + collection_id: str, + *, + tokenization_rules: List['TokenDictRule'] = None, + **kwargs) -> 'DetailedResponse': """ Create tokenization dictionary. @@ -1028,7 +1100,7 @@ def create_tokenization_dictionary(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param list[TokenDictRule] tokenization_rules: (optional) An array of + :param List[TokenDictRule] tokenization_rules: (optional) An array of tokenization rules. Each rule contains, the original `text` string, component `tokens`, any alternate character set `readings`, and which `part_of_speech` the text is from. @@ -1049,8 +1121,10 @@ def create_tokenization_dictionary(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'create_tokenization_dictionary') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_tokenization_dictionary') headers.update(sdk_headers) params = {'version': self.version} @@ -1063,13 +1137,14 @@ def create_tokenization_dictionary(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_tokenization_dictionary(self, environment_id, collection_id, - **kwargs): + def delete_tokenization_dictionary(self, environment_id: str, + collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete tokenization dictionary. @@ -1090,8 +1165,10 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'delete_tokenization_dictionary') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_tokenization_dictionary') headers.update(sdk_headers) params = {'version': self.version} @@ -1101,12 +1178,13 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_stopword_list_status(self, environment_id, collection_id, **kwargs): + def get_stopword_list_status(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get stopword list status. @@ -1127,8 +1205,9 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -1138,18 +1217,18 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_stopword_list(self, - environment_id, - collection_id, - stopword_file, + environment_id: str, + collection_id: str, + stopword_file: BinaryIO, *, - stopword_filename=None, - **kwargs): + stopword_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Create stopword list. @@ -1157,7 +1236,7 @@ def create_stopword_list(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param file stopword_file: The content of the stopword list to ingest. + :param TextIO stopword_file: The content of the stopword list to ingest. :param str stopword_filename: (optional) The filename for stopword_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1174,7 +1253,9 @@ def create_stopword_list(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1193,12 +1274,13 @@ def create_stopword_list(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_stopword_list(self, environment_id, collection_id, **kwargs): + def delete_stopword_list(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom stopword list. @@ -1220,7 +1302,9 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1230,8 +1314,8 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -1240,14 +1324,14 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): ######################### def add_document(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> 'DetailedResponse': """ Add a document. @@ -1274,7 +1358,7 @@ def add_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1298,7 +1382,9 @@ def add_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1312,6 +1398,7 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents'.format( @@ -1320,13 +1407,13 @@ def add_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_document_status(self, environment_id, collection_id, document_id, - **kwargs): + def get_document_status(self, environment_id: str, collection_id: str, + document_id: str, **kwargs) -> 'DetailedResponse': """ Get document details. @@ -1353,7 +1440,9 @@ def get_document_status(self, environment_id, collection_id, document_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1363,21 +1452,21 @@ def get_document_status(self, environment_id, collection_id, document_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_document(self, - environment_id, - collection_id, - document_id, + environment_id: str, + collection_id: str, + document_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> 'DetailedResponse': """ Update a document. @@ -1389,7 +1478,7 @@ def update_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1415,7 +1504,9 @@ def update_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1429,6 +1520,7 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( @@ -1437,13 +1529,13 @@ def update_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_document(self, environment_id, collection_id, document_id, - **kwargs): + def delete_document(self, environment_id: str, collection_id: str, + document_id: str, **kwargs) -> 'DetailedResponse': """ Delete a document. @@ -1469,7 +1561,9 @@ def delete_document(self, environment_id, collection_id, document_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1479,8 +1573,8 @@ def delete_document(self, environment_id, collection_id, document_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1489,31 +1583,31 @@ def delete_document(self, environment_id, collection_id, document_id, ######################### def query(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - bias=None, - spelling_suggestions=None, - x_watson_logging_opt_out=None, - **kwargs): + 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': """ Query a collection. @@ -1610,7 +1704,9 @@ def query(self, headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query') headers.update(sdk_headers) params = {'version': self.version} @@ -1644,33 +1740,33 @@ def query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def query_notices(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - **kwargs): + 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': """ Query system notices. @@ -1699,20 +1795,20 @@ def query_notices(self, possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] return_: (optional) A comma-separated list of the portion + :param List[str] return_: (optional) A comma-separated list of the portion of the document hierarchy to return. :param int offset: (optional) The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: (optional) When true, a highlight field is returned for each result which contains the fields which match the query with `` tags around the matching query terms. - :param list[str] passages_fields: (optional) A comma-separated list of + :param List[str] passages_fields: (optional) A comma-separated list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int passages_count: (optional) The maximum number of passages to @@ -1727,13 +1823,13 @@ def query_notices(self, :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: (optional) A comma-separated list of + :param List[str] similar_document_ids: (optional) A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. - :param list[str] similar_fields: (optional) A comma-separated list of field + :param List[str] similar_fields: (optional) A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers @@ -1749,7 +1845,9 @@ def query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = { @@ -1778,36 +1876,36 @@ def query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def federated_query(self, - environment_id, - collection_ids, + environment_id: str, + collection_ids: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - bias=None, - x_watson_logging_opt_out=None, - **kwargs): + 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': """ Query multiple collections. @@ -1893,11 +1991,15 @@ def federated_query(self, if environment_id is None: raise ValueError('environment_id must be provided') + if collection_ids is None: + raise ValueError('collection_ids must be provided') headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -1931,29 +2033,29 @@ def federated_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def federated_query_notices(self, - environment_id, - collection_ids, + environment_id: str, + collection_ids: List[str], *, - filter=None, - query=None, - natural_language_query=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - **kwargs): + 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': """ Query multiple collection system notices. @@ -1964,7 +2066,7 @@ def federated_query_notices(self, for more details on the query language. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs + :param List[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for @@ -1981,13 +2083,13 @@ def federated_query_notices(self, possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] return_: (optional) A comma-separated list of the portion + :param List[str] return_: (optional) A comma-separated list of the portion of the document hierarchy to return. :param int offset: (optional) The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2001,13 +2103,13 @@ def federated_query_notices(self, :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: (optional) A comma-separated list of + :param List[str] similar_document_ids: (optional) A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. - :param list[str] similar_fields: (optional) A comma-separated list of field + :param List[str] similar_fields: (optional) A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers @@ -2023,8 +2125,9 @@ def federated_query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = { @@ -2050,19 +2153,19 @@ def federated_query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_autocompletion(self, - environment_id, - collection_id, - prefix, + environment_id: str, + collection_id: str, + prefix: str, *, - field=None, - count=None, - **kwargs): + field: str = None, + count: int = None, + **kwargs) -> 'DetailedResponse': """ Get Autocomplete Suggestions. @@ -2094,7 +2197,9 @@ def get_autocompletion(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = { @@ -2109,8 +2214,8 @@ def get_autocompletion(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2118,7 +2223,8 @@ def get_autocompletion(self, # Training data ######################### - def list_training_data(self, environment_id, collection_id, **kwargs): + def list_training_data(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ List training data. @@ -2139,7 +2245,9 @@ def list_training_data(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2149,19 +2257,19 @@ def list_training_data(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def add_training_data(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - natural_language_query=None, - filter=None, - examples=None, - **kwargs): + natural_language_query: str = None, + filter: str = None, + examples: List['TrainingExample'] = None, + **kwargs) -> 'DetailedResponse': """ Add query to training data. @@ -2174,7 +2282,7 @@ def add_training_data(self, the new training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -2191,7 +2299,9 @@ def add_training_data(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2208,12 +2318,13 @@ def add_training_data(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_all_training_data(self, environment_id, collection_id, **kwargs): + def delete_all_training_data(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete all training data. @@ -2234,8 +2345,9 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -2245,13 +2357,13 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_training_data(self, environment_id, collection_id, query_id, - **kwargs): + def get_training_data(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ Get details about a query. @@ -2276,7 +2388,9 @@ def get_training_data(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2286,13 +2400,13 @@ def get_training_data(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_training_data(self, environment_id, collection_id, query_id, - **kwargs): + def delete_training_data(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ Delete a training data query. @@ -2317,7 +2431,9 @@ def delete_training_data(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2327,13 +2443,13 @@ def delete_training_data(self, environment_id, collection_id, query_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def list_training_examples(self, environment_id, collection_id, query_id, - **kwargs): + def list_training_examples(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ List examples for a training data query. @@ -2357,8 +2473,9 @@ def list_training_examples(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -2368,20 +2485,20 @@ def list_training_examples(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_training_example(self, - environment_id, - collection_id, - query_id, + environment_id: str, + collection_id: str, + query_id: str, *, - document_id=None, - cross_reference=None, - relevance=None, - **kwargs): + document_id: str = None, + cross_reference: str = None, + relevance: int = None, + **kwargs) -> 'DetailedResponse': """ Add example to training data query. @@ -2410,8 +2527,9 @@ def create_training_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -2428,13 +2546,14 @@ def create_training_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_training_example(self, environment_id, collection_id, query_id, - example_id, **kwargs): + 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. @@ -2461,8 +2580,9 @@ def delete_training_example(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -2473,20 +2593,20 @@ def delete_training_example(self, environment_id, collection_id, query_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def update_training_example(self, - environment_id, - collection_id, - query_id, - example_id, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, *, - cross_reference=None, - relevance=None, - **kwargs): + cross_reference: str = None, + relevance: int = None, + **kwargs) -> 'DetailedResponse': """ Change label or cross reference for example. @@ -2515,8 +2635,9 @@ def update_training_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = {'version': self.version} @@ -2530,13 +2651,14 @@ def update_training_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_example(self, environment_id, collection_id, query_id, - example_id, **kwargs): + 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. @@ -2563,7 +2685,9 @@ def get_training_example(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2574,8 +2698,8 @@ def get_training_example(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2583,7 +2707,8 @@ def get_training_example(self, environment_id, collection_id, query_id, # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -2607,7 +2732,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version, 'customer_id': customer_id} @@ -2616,8 +2743,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -2625,13 +2752,14 @@ def delete_user_data(self, customer_id, **kwargs): # Events and feedback ######################### - def create_event(self, type, data, **kwargs): + def create_event(self, type: str, data: 'EventData', + **kwargs) -> 'DetailedResponse': """ Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set - were "clicked" by a user and when that click occured. + were "clicked" by a user and when that click occurred. :param str type: The event type to be created. :param EventData data: Query event data object. @@ -2649,7 +2777,9 @@ def create_event(self, type, data, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2661,19 +2791,19 @@ def create_event(self, type, data, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def query_log(self, *, - filter=None, - query=None, - count=None, - offset=None, - sort=None, - **kwargs): + filter: str = None, + query: str = None, + count: int = None, + offset: int = None, + sort: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Search the query and event log. @@ -2693,7 +2823,7 @@ def query_log(self, beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2705,7 +2835,9 @@ def query_log(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = { @@ -2721,17 +2853,17 @@ def query_log(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries over time. @@ -2752,7 +2884,9 @@ def get_metrics_query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = { @@ -2766,17 +2900,17 @@ def get_metrics_query(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query_event(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries with an event over time. @@ -2798,8 +2932,9 @@ def get_metrics_query_event(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = { @@ -2813,17 +2948,17 @@ def get_metrics_query_event(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query_no_results(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries with no search results over time. @@ -2844,8 +2979,10 @@ def get_metrics_query_no_results(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_query_no_results') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_no_results') headers.update(sdk_headers) params = { @@ -2859,17 +2996,17 @@ def get_metrics_query_no_results(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_event_rate(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Percentage of queries with an associated event. @@ -2891,8 +3028,9 @@ def get_metrics_event_rate(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - '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 = { @@ -2906,12 +3044,13 @@ def get_metrics_event_rate(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_metrics_query_token_event(self, *, count=None, **kwargs): + def get_metrics_query_token_event(self, *, count: int = None, + **kwargs) -> 'DetailedResponse': """ Most frequent query tokens with an event. @@ -2930,8 +3069,10 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_query_token_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_token_event') headers.update(sdk_headers) params = {'version': self.version, 'count': count} @@ -2940,8 +3081,8 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2949,7 +3090,8 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): # Credentials ######################### - def list_credentials(self, environment_id, **kwargs): + def list_credentials(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ List credentials. @@ -2969,7 +3111,9 @@ def list_credentials(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -2979,18 +3123,18 @@ def list_credentials(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_credentials(self, - environment_id, + environment_id: str, *, - source_type=None, - credential_details=None, - status=None, - **kwargs): + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None, + **kwargs) -> 'DetailedResponse': """ Create credentials. @@ -3032,7 +3176,9 @@ def create_credentials(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3049,12 +3195,13 @@ def create_credentials(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_credentials(self, environment_id, credential_id, **kwargs): + def get_credentials(self, environment_id: str, credential_id: str, + **kwargs) -> 'DetailedResponse': """ View Credentials. @@ -3078,7 +3225,9 @@ def get_credentials(self, environment_id, credential_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3088,19 +3237,19 @@ def get_credentials(self, environment_id, credential_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_credentials(self, - environment_id, - credential_id, + environment_id: str, + credential_id: str, *, - source_type=None, - credential_details=None, - status=None, - **kwargs): + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None, + **kwargs) -> 'DetailedResponse': """ Update credentials. @@ -3145,7 +3294,9 @@ def update_credentials(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3162,12 +3313,13 @@ def update_credentials(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_credentials(self, environment_id, credential_id, **kwargs): + def delete_credentials(self, environment_id: str, credential_id: str, + **kwargs) -> 'DetailedResponse': """ Delete credentials. @@ -3189,7 +3341,9 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3199,8 +3353,8 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3208,7 +3362,8 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): # gatewayConfiguration ######################### - def list_gateways(self, environment_id, **kwargs): + def list_gateways(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ List Gateways. @@ -3226,7 +3381,9 @@ def list_gateways(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3236,12 +3393,13 @@ def list_gateways(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_gateway(self, environment_id, *, name=None, **kwargs): + def create_gateway(self, environment_id: str, *, name: str = None, + **kwargs) -> 'DetailedResponse': """ Create Gateway. @@ -3260,7 +3418,9 @@ def create_gateway(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3273,12 +3433,13 @@ def create_gateway(self, environment_id, *, name=None, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_gateway(self, environment_id, gateway_id, **kwargs): + def get_gateway(self, environment_id: str, gateway_id: str, + **kwargs) -> 'DetailedResponse': """ List Gateway Details. @@ -3299,7 +3460,9 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3309,12 +3472,13 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_gateway(self, environment_id, gateway_id, **kwargs): + def delete_gateway(self, environment_id: str, gateway_id: str, + **kwargs) -> 'DetailedResponse': """ Delete Gateway. @@ -3335,7 +3499,9 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', '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 = {'version': self.version} @@ -3345,8 +3511,8 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3426,17 +3592,21 @@ class AggregationResult(): :attr str key: (optional) Key that matched the aggregation type. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryAggregation] aggregations: (optional) Aggregations returned in + :attr List[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ - def __init__(self, *, key=None, matching_results=None, aggregations=None): + def __init__(self, + *, + key: str = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a AggregationResult object. :param str key: (optional) Key that matched the aggregation type. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations + :param List[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ self.key = key @@ -3444,7 +3614,7 @@ def __init__(self, *, key=None, matching_results=None, aggregations=None): self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AggregationResult': """Initialize a AggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'aggregations'] @@ -3464,7 +3634,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AggregationResult 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, 'key') and self.key is not None: @@ -3476,91 +3651,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this AggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Calculation(): - """ - Calculation. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr float value: (optional) Value of the aggregation. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - value=None): - """ - Initialize a Calculation object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param float value: (optional) Value of the aggregation. - """ - self.field = field - self.value = value - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Calculation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Calculation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'value' in _dict: - args['value'] = _dict.get('value') - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this Calculation object.""" + def __str__(self) -> str: + """Return a `str` version of this AggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AggregationResult') -> 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): + def __ne__(self, other: 'AggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3595,19 +3700,19 @@ class Collection(): def __init__(self, *, - collection_id=None, - name=None, - description=None, - created=None, - updated=None, - status=None, - configuration_id=None, - language=None, - document_counts=None, - disk_usage=None, - training_status=None, - crawl_status=None, - smart_document_understanding=None): + 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: """ Initialize a Collection object. @@ -3650,7 +3755,7 @@ def __init__(self, self.smart_document_understanding = smart_document_understanding @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = [ @@ -3697,7 +3802,12 @@ def _from_dict(cls, _dict): _dict.get('smart_document_understanding')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -3734,17 +3844,21 @@ def _to_dict(self): ) return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3765,7 +3879,7 @@ class CollectionCrawlStatus(): status information. """ - def __init__(self, *, source_crawl=None): + def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: """ Initialize a CollectionCrawlStatus object. @@ -3775,7 +3889,7 @@ def __init__(self, *, source_crawl=None): self.source_crawl = source_crawl @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} valid_keys = ['source_crawl'] @@ -3789,24 +3903,33 @@ def _from_dict(cls, _dict): _dict.get('source_crawl')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionCrawlStatus 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, 'source_crawl') and self.source_crawl is not None: _dict['source_crawl'] = self.source_crawl._to_dict() return _dict - def __str__(self): + 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 CollectionCrawlStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionCrawlStatus') -> 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): + def __ne__(self, other: 'CollectionCrawlStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3818,7 +3941,7 @@ class CollectionDiskUsage(): :attr int used_bytes: (optional) Number of bytes used by the collection. """ - def __init__(self, *, used_bytes=None): + def __init__(self, *, used_bytes: int = None) -> None: """ Initialize a CollectionDiskUsage object. @@ -3827,7 +3950,7 @@ def __init__(self, *, used_bytes=None): self.used_bytes = used_bytes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} valid_keys = ['used_bytes'] @@ -3840,24 +3963,33 @@ def _from_dict(cls, _dict): args['used_bytes'] = _dict.get('used_bytes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDiskUsage 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, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes return _dict - def __str__(self): + 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 CollectionDiskUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionDiskUsage') -> 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): + def __ne__(self, other: 'CollectionDiskUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3871,7 +4003,8 @@ class CollectionUsage(): environment. """ - def __init__(self, *, available=None, maximum_allowed=None): + def __init__(self, *, available: int = None, + maximum_allowed: int = None) -> None: """ Initialize a CollectionUsage object. @@ -3884,7 +4017,7 @@ def __init__(self, *, available=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionUsage': """Initialize a CollectionUsage object from a json dictionary.""" args = {} valid_keys = ['available', 'maximum_allowed'] @@ -3899,7 +4032,12 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionUsage 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, 'available') and self.available is not None: @@ -3909,17 +4047,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 CollectionUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionUsage') -> 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): + def __ne__(self, other: 'CollectionUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3928,21 +4070,21 @@ class Completions(): """ An object containing an array of autocompletion suggestions. - :attr list[str] completions: (optional) Array of autcomplete suggestion based on + :attr List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions=None): + def __init__(self, *, completions: List[str] = None) -> None: """ Initialize a Completions object. - :param list[str] completions: (optional) Array of autcomplete suggestion + :param List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ self.completions = completions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} valid_keys = ['completions'] @@ -3955,24 +4097,33 @@ def _from_dict(cls, _dict): args['completions'] = _dict.get('completions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: _dict['completions'] = self.completions return _dict - def __str__(self): + 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 Completions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Completions') -> 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): + def __ne__(self, other: 'Completions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3991,9 +4142,9 @@ class Configuration(): :attr 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 + :attr List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :attr list[NormalizationOperation] normalizations: (optional) Defines operations + :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 @@ -4001,16 +4152,16 @@ class Configuration(): """ def __init__(self, - name, + name: str, *, - configuration_id=None, - created=None, - updated=None, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None): + 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: """ Initialize a Configuration object. @@ -4024,9 +4175,9 @@ def __init__(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :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. @@ -4044,7 +4195,7 @@ def __init__(self, self.source = source @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Configuration': """Initialize a Configuration object from a json dictionary.""" args = {} valid_keys = [ @@ -4085,7 +4236,12 @@ def _from_dict(cls, _dict): args['source'] = Source._from_dict(_dict.get('source')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Configuration 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, @@ -4111,17 +4267,21 @@ def _to_dict(self): _dict['source'] = self.source._to_dict() return _dict - def __str__(self): + 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 Configuration object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Configuration') -> 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): + def __ne__(self, other: 'Configuration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4135,7 +4295,7 @@ class Conversions(): :attr HtmlSettings html: (optional) A list of HTML conversion settings. :attr SegmentSettings segment: (optional) A list of Document Segmentation settings. - :attr list[NormalizationOperation] json_normalizations: (optional) Defines + :attr 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 @@ -4148,12 +4308,12 @@ class Conversions(): def __init__(self, *, - pdf=None, - word=None, - html=None, - segment=None, - json_normalizations=None, - image_text_recognition=None): + pdf: 'PdfSettings' = None, + word: 'WordSettings' = None, + html: 'HtmlSettings' = None, + segment: 'SegmentSettings' = None, + json_normalizations: List['NormalizationOperation'] = None, + image_text_recognition: bool = None) -> None: """ Initialize a Conversions object. @@ -4162,7 +4322,7 @@ def __init__(self, :param HtmlSettings html: (optional) A list of HTML conversion settings. :param SegmentSettings segment: (optional) A list of Document Segmentation settings. - :param 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. @@ -4181,7 +4341,7 @@ def __init__(self, self.image_text_recognition = image_text_recognition @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Conversions': """Initialize a Conversions object from a json dictionary.""" args = {} valid_keys = [ @@ -4210,7 +4370,12 @@ def _from_dict(cls, _dict): args['image_text_recognition'] = _dict.get('image_text_recognition') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Conversions 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, 'pdf') and self.pdf is not None: @@ -4232,17 +4397,21 @@ def _to_dict(self): _dict['image_text_recognition'] = self.image_text_recognition return _dict - def __str__(self): + 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 Conversions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Conversions') -> 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): + def __ne__(self, other: 'Conversions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4255,7 +4424,7 @@ class CreateEventResponse(): :attr EventData data: (optional) Query event data object. """ - def __init__(self, *, type=None, data=None): + def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: """ Initialize a CreateEventResponse object. @@ -4266,7 +4435,7 @@ def __init__(self, *, type=None, data=None): self.data = data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': """Initialize a CreateEventResponse object from a json dictionary.""" args = {} valid_keys = ['type', 'data'] @@ -4281,7 +4450,12 @@ def _from_dict(cls, _dict): args['data'] = EventData._from_dict(_dict.get('data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEventResponse 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, 'type') and self.type is not None: @@ -4290,17 +4464,21 @@ def _to_dict(self): _dict['data'] = self.data._to_dict() return _dict - def __str__(self): - """Return a `str` version of this CreateEventResponse object.""" + 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 CreateEventResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateEventResponse') -> 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): + def __ne__(self, other: 'CreateEventResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4396,25 +4574,25 @@ class CredentialDetails(): def __init__(self, *, - credential_type=None, - client_id=None, - enterprise_id=None, - url=None, - username=None, - organization_url=None, - site_collection_path=None, - client_secret=None, - public_key_id=None, - private_key=None, - passphrase=None, - password=None, - gateway_id=None, - source_version=None, - web_application_url=None, - domain=None, - endpoint=None, - access_key_id=None, - secret_access_key=None): + 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: """ Initialize a CredentialDetails object. @@ -4522,7 +4700,7 @@ def __init__(self, self.secret_access_key = secret_access_key @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CredentialDetails': """Initialize a CredentialDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -4577,7 +4755,12 @@ def _from_dict(cls, _dict): args['secret_access_key'] = _dict.get('secret_access_key') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CredentialDetails 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, @@ -4626,17 +4809,21 @@ def _to_dict(self): _dict['secret_access_key'] = self.secret_access_key return _dict - def __str__(self): + 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 CredentialDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CredentialDetails') -> 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): + def __ne__(self, other: 'CredentialDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4696,10 +4883,10 @@ class Credentials(): def __init__(self, *, - credential_id=None, - source_type=None, - credential_details=None, - status=None): + credential_id: str = None, + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None) -> None: """ Initialize a Credentials object. @@ -4731,7 +4918,7 @@ def __init__(self, self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Credentials': """Initialize a Credentials object from a json dictionary.""" args = {} valid_keys = [ @@ -4753,7 +4940,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Credentials 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, 'credential_id') and self.credential_id is not None: @@ -4768,17 +4960,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 Credentials object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Credentials') -> 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): + def __ne__(self, other: 'Credentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4815,21 +5011,21 @@ class CredentialsList(): """ Object containing array of credential definitions. - :attr list[Credentials] credentials: (optional) An array of credential + :attr List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ - def __init__(self, *, credentials=None): + def __init__(self, *, credentials: List['Credentials'] = None) -> None: """ Initialize a CredentialsList object. - :param list[Credentials] credentials: (optional) An array of credential + :param List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CredentialsList': """Initialize a CredentialsList object from a json dictionary.""" args = {} valid_keys = ['credentials'] @@ -4844,24 +5040,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CredentialsList 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, 'credentials') and self.credentials is not None: _dict['credentials'] = [x._to_dict() for x in self.credentials] return _dict - def __str__(self): + 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 CredentialsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CredentialsList') -> 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): + def __ne__(self, other: 'CredentialsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4876,7 +5081,7 @@ class DeleteCollectionResponse(): deletion operation is `deleted`. """ - def __init__(self, collection_id, status): + def __init__(self, collection_id: str, status: str) -> None: """ Initialize a DeleteCollectionResponse object. @@ -4889,7 +5094,7 @@ def __init__(self, collection_id, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'status'] @@ -4912,7 +5117,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteCollectionResponse 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, 'collection_id') and self.collection_id is not None: @@ -4921,17 +5131,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteCollectionResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteCollectionResponse') -> 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): + def __ne__(self, other: 'DeleteCollectionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4950,17 +5164,21 @@ class DeleteConfigurationResponse(): :attr str configuration_id: The unique identifier for the configuration. :attr 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. + :attr List[Notice] notices: (optional) An array of notice messages, if any. """ - def __init__(self, configuration_id, status, *, notices=None): + def __init__(self, + configuration_id: str, + status: str, + *, + notices: List['Notice'] = None) -> None: """ Initialize a DeleteConfigurationResponse object. :param str configuration_id: The unique identifier for the configuration. :param str status: Status of the configuration. A deleted configuration has the status deleted. - :param list[Notice] notices: (optional) An array of notice messages, if + :param List[Notice] notices: (optional) An array of notice messages, if any. """ self.configuration_id = configuration_id @@ -4968,7 +5186,7 @@ def __init__(self, configuration_id, status, *, notices=None): self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} valid_keys = ['configuration_id', 'status', 'notices'] @@ -4995,7 +5213,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteConfigurationResponse 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, @@ -5007,17 +5230,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DeleteConfigurationResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteConfigurationResponse') -> 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): + def __ne__(self, other: 'DeleteConfigurationResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5037,7 +5264,8 @@ class DeleteCredentials(): :attr str status: (optional) The status of the deletion request. """ - def __init__(self, *, credential_id=None, status=None): + def __init__(self, *, credential_id: str = None, + status: str = None) -> None: """ Initialize a DeleteCredentials object. @@ -5049,7 +5277,7 @@ def __init__(self, *, credential_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': """Initialize a DeleteCredentials object from a json dictionary.""" args = {} valid_keys = ['credential_id', 'status'] @@ -5064,7 +5292,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteCredentials 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, 'credential_id') and self.credential_id is not None: @@ -5073,17 +5306,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteCredentials object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteCredentials') -> 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): + def __ne__(self, other: 'DeleteCredentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5103,7 +5340,7 @@ class DeleteDocumentResponse(): status deleted. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5115,7 +5352,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -5130,7 +5367,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: @@ -5139,17 +5381,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteDocumentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteDocumentResponse') -> 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): + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5168,7 +5414,7 @@ class DeleteEnvironmentResponse(): :attr str status: Status of the environment. """ - def __init__(self, environment_id, status): + def __init__(self, environment_id: str, status: str) -> None: """ Initialize a DeleteEnvironmentResponse object. @@ -5179,7 +5425,7 @@ def __init__(self, environment_id, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} valid_keys = ['environment_id', 'status'] @@ -5202,7 +5448,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteEnvironmentResponse 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, 'environment_id') and self.environment_id is not None: @@ -5211,17 +5462,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteEnvironmentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteEnvironmentResponse') -> 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): + def __ne__(self, other: 'DeleteEnvironmentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5242,7 +5497,10 @@ class DiskUsage(): the environment's disk capacity. """ - def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): + def __init__(self, + *, + used_bytes: int = None, + maximum_allowed_bytes: int = None) -> None: """ Initialize a DiskUsage object. @@ -5255,7 +5513,7 @@ def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): self.maximum_allowed_bytes = maximum_allowed_bytes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DiskUsage': """Initialize a DiskUsage object from a json dictionary.""" args = {} valid_keys = ['used_bytes', 'maximum_allowed_bytes'] @@ -5270,7 +5528,12 @@ def _from_dict(cls, _dict): args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DiskUsage 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, 'used_bytes') and self.used_bytes is not None: @@ -5280,17 +5543,21 @@ def _to_dict(self): _dict['maximum_allowed_bytes'] = self.maximum_allowed_bytes return _dict - def __str__(self): + 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 DiskUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DiskUsage') -> 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): + def __ne__(self, other: 'DiskUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5305,11 +5572,15 @@ class DocumentAccepted(): 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 + :attr List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, *, document_id=None, status=None, notices=None): + def __init__(self, + *, + document_id: str = None, + status: str = None, + notices: List['Notice'] = None) -> None: """ Initialize a DocumentAccepted object. @@ -5319,7 +5590,7 @@ def __init__(self, *, document_id=None, status=None, notices=None): 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. - :param list[Notice] notices: (optional) Array of notices produced by the + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ self.document_id = document_id @@ -5327,7 +5598,7 @@ def __init__(self, *, document_id=None, status=None, notices=None): self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status', 'notices'] @@ -5346,7 +5617,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: @@ -5357,17 +5633,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DocumentAccepted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAccepted') -> 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): + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5397,10 +5677,10 @@ class DocumentCounts(): def __init__(self, *, - available=None, - processing=None, - failed=None, - pending=None): + available: int = None, + processing: int = None, + failed: int = None, + pending: int = None) -> None: """ Initialize a DocumentCounts object. @@ -5419,7 +5699,7 @@ def __init__(self, self.pending = pending @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentCounts': """Initialize a DocumentCounts object from a json dictionary.""" args = {} valid_keys = ['available', 'processing', 'failed', 'pending'] @@ -5438,7 +5718,12 @@ def _from_dict(cls, _dict): args['pending'] = _dict.get('pending') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentCounts 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, 'available') and self.available is not None: @@ -5451,17 +5736,21 @@ def _to_dict(self): _dict['pending'] = self.pending return _dict - def __str__(self): + 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 DocumentCounts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentCounts') -> 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): + def __ne__(self, other: 'DocumentCounts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5479,27 +5768,27 @@ class DocumentStatus(): :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: Array of notices produced by the document-ingestion + :attr List[Notice] notices: Array of notices produced by the document-ingestion process. """ def __init__(self, - document_id, - status, - status_description, - notices, + document_id: str, + status: str, + status_description: str, + notices: List['Notice'], *, - configuration_id=None, - filename=None, - file_type=None, - sha1=None): + configuration_id: str = None, + filename: str = None, + file_type: str = None, + sha1: str = None) -> None: """ Initialize a DocumentStatus object. :param str document_id: The unique identifier of the document. :param str status: Status of the document in the ingestion process. :param str status_description: Description of the document status. - :param list[Notice] notices: Array of notices produced by the + :param List[Notice] notices: Array of notices produced by the document-ingestion process. :param str configuration_id: (optional) The unique identifier for the configuration. @@ -5519,7 +5808,7 @@ def __init__(self, self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -5567,7 +5856,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentStatus 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, 'document_id') and self.document_id is not None: @@ -5591,17 +5885,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DocumentStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentStatus') -> 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): + def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5657,14 +5955,14 @@ class Enrichment(): """ def __init__(self, - destination_field, - source_field, - enrichment, + destination_field: str, + source_field: str, + enrichment: str, *, - description=None, - overwrite=None, - ignore_downstream_errors=None, - options=None): + description: str = None, + overwrite: bool = None, + ignore_downstream_errors: bool = None, + options: 'EnrichmentOptions' = None) -> None: """ Initialize a Enrichment object. @@ -5702,7 +6000,7 @@ def __init__(self, self.options = options @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} valid_keys = [ @@ -5743,7 +6041,12 @@ def _from_dict(cls, _dict): args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Enrichment 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, 'description') and self.description is not None: @@ -5764,17 +6067,21 @@ def _to_dict(self): _dict['options'] = self.options._to_dict() return _dict - def __str__(self): + 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 Enrichment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Enrichment') -> 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): + def __ne__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5795,7 +6102,11 @@ class EnrichmentOptions(): element extraction model to use. Models available are: `contract`. """ - def __init__(self, *, features=None, language=None, model=None): + def __init__(self, + *, + features: 'NluEnrichmentFeatures' = None, + language: str = None, + model: str = None) -> None: """ Initialize a EnrichmentOptions object. @@ -5815,7 +6126,7 @@ def __init__(self, *, features=None, language=None, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} valid_keys = ['features', 'language', 'model'] @@ -5833,7 +6144,12 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichmentOptions 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, 'features') and self.features is not None: @@ -5844,17 +6160,21 @@ def _to_dict(self): _dict['model'] = self.model return _dict - def __str__(self): + 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 EnrichmentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EnrichmentOptions') -> 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): + def __ne__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5906,17 +6226,17 @@ class Environment(): def __init__(self, *, - environment_id=None, - name=None, - description=None, - created=None, - updated=None, - status=None, - read_only=None, - size=None, - requested_size=None, - index_capacity=None, - search_status=None): + 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: """ Initialize a Environment object. @@ -5956,7 +6276,7 @@ def __init__(self, self.search_status = search_status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} valid_keys = [ @@ -5995,7 +6315,12 @@ def _from_dict(cls, _dict): _dict.get('search_status')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Environment 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, 'environment_id') and self.environment_id is not None: @@ -6022,17 +6347,21 @@ def _to_dict(self): _dict['search_status'] = self.search_status._to_dict() return _dict - def __str__(self): + 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 Environment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Environment') -> 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): + def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6072,7 +6401,8 @@ class EnvironmentDocuments(): environment's capacity. """ - def __init__(self, *, indexed=None, maximum_allowed=None): + def __init__(self, *, indexed: int = None, + maximum_allowed: int = None) -> None: """ Initialize a EnvironmentDocuments object. @@ -6085,7 +6415,7 @@ def __init__(self, *, indexed=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} valid_keys = ['indexed', 'maximum_allowed'] @@ -6100,7 +6430,12 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnvironmentDocuments 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, 'indexed') and self.indexed is not None: @@ -6110,17 +6445,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 EnvironmentDocuments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EnvironmentDocuments') -> 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): + def __ne__(self, other: 'EnvironmentDocuments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6147,14 +6486,14 @@ class EventData(): """ def __init__(self, - environment_id, - session_token, - collection_id, - document_id, + environment_id: str, + session_token: str, + collection_id: str, + document_id: str, *, - client_timestamp=None, - display_rank=None, - query_id=None): + client_timestamp: datetime = None, + display_rank: int = None, + query_id: str = None) -> None: """ Initialize a EventData object. @@ -6184,7 +6523,7 @@ def __init__(self, self.query_id = query_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EventData': """Initialize a EventData object from a json dictionary.""" args = {} valid_keys = [ @@ -6229,7 +6568,12 @@ def _from_dict(cls, _dict): args['query_id'] = _dict.get('query_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EventData 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, 'environment_id') and self.environment_id is not None: @@ -6250,17 +6594,21 @@ def _to_dict(self): _dict['query_id'] = self.query_id return _dict - def __str__(self): + 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 EventData object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EventData') -> 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): + def __ne__(self, other: 'EventData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6271,21 +6619,24 @@ class Expansion(): 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 + :attr 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 + :attr 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, *, input_terms=None): + def __init__(self, + expanded_terms: List[str], + *, + input_terms: List[str] = None) -> None: """ Initialize a Expansion object. - :param list[str] expanded_terms: A list of terms that this expansion will + :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. - :param list[str] input_terms: (optional) A list of terms that will be + :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. """ @@ -6293,7 +6644,7 @@ def __init__(self, expanded_terms, *, input_terms=None): self.expanded_terms = expanded_terms @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} valid_keys = ['input_terms', 'expanded_terms'] @@ -6312,7 +6663,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansion 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_terms') and self.input_terms is not None: @@ -6321,17 +6677,21 @@ def _to_dict(self): _dict['expanded_terms'] = self.expanded_terms return _dict - def __str__(self): + 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 Expansion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Expansion') -> 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): + def __ne__(self, other: 'Expansion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6340,7 +6700,7 @@ class Expansions(): """ The query expansion definitions for the specified collection. - :attr list[Expansion] expansions: An array of query expansion definitions. + :attr 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 @@ -6355,11 +6715,11 @@ class Expansions(): **expanded_terms** array. """ - def __init__(self, expansions): + def __init__(self, expansions: List['Expansion']) -> None: """ Initialize a Expansions object. - :param 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 @@ -6376,7 +6736,7 @@ def __init__(self, expansions): self.expansions = expansions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} valid_keys = ['expansions'] @@ -6395,24 +6755,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansions 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, 'expansions') and self.expansions is not None: _dict['expansions'] = [x._to_dict() for x in self.expansions] return _dict - def __str__(self): + 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 Expansions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Expansions') -> 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): + def __ne__(self, other: 'Expansions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6425,7 +6794,7 @@ class Field(): :attr str type: (optional) The type of the field. """ - def __init__(self, *, field=None, type=None): + def __init__(self, *, field: str = None, type: str = None) -> None: """ Initialize a Field object. @@ -6436,7 +6805,7 @@ def __init__(self, *, field=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} valid_keys = ['field', 'type'] @@ -6451,7 +6820,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Field 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, 'field') and self.field is not None: @@ -6460,17 +6834,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Field') -> 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): + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6491,70 +6869,6 @@ class TypeEnum(Enum): BINARY = "binary" -class Filter(): - """ - Filter. - - :attr str match: (optional) The match the aggregated results queried for. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - match=None): - """ - Initialize a Filter object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str match: (optional) The match the aggregated results queried for. - """ - self.match = match - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Filter object from a json dictionary.""" - args = {} - valid_keys = ['match'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Filter: ' + - ', '.join(bad_keys)) - if 'match' in _dict: - args['match'] = _dict.get('match') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - return _dict - - def __str__(self): - """Return a `str` version of this Filter object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FontSetting(): """ Font matching configuration. @@ -6570,12 +6884,12 @@ class FontSetting(): def __init__(self, *, - level=None, - min_size=None, - max_size=None, - bold=None, - italic=None, - name=None): + level: int = None, + min_size: int = None, + max_size: int = None, + bold: bool = None, + italic: bool = None, + name: str = None) -> None: """ Initialize a FontSetting object. @@ -6597,7 +6911,7 @@ def __init__(self, self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FontSetting': """Initialize a FontSetting object from a json dictionary.""" args = {} valid_keys = ['level', 'min_size', 'max_size', 'bold', 'italic', 'name'] @@ -6620,7 +6934,12 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FontSetting 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, 'level') and self.level is not None: @@ -6637,17 +6956,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 FontSetting object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FontSetting') -> 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): + def __ne__(self, other: 'FontSetting') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6669,11 +6992,11 @@ class Gateway(): def __init__(self, *, - gateway_id=None, - name=None, - status=None, - token=None, - token_id=None): + gateway_id: str = None, + name: str = None, + status: str = None, + token: str = None, + token_id: str = None) -> None: """ Initialize a Gateway object. @@ -6695,7 +7018,7 @@ def __init__(self, self.token_id = token_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Gateway': """Initialize a Gateway object from a json dictionary.""" args = {} valid_keys = ['gateway_id', 'name', 'status', 'token', 'token_id'] @@ -6716,7 +7039,12 @@ def _from_dict(cls, _dict): args['token_id'] = _dict.get('token_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Gateway 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, 'gateway_id') and self.gateway_id is not None: @@ -6731,17 +7059,21 @@ def _to_dict(self): _dict['token_id'] = self.token_id return _dict - def __str__(self): + 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 Gateway object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Gateway') -> 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): + def __ne__(self, other: 'Gateway') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6762,7 +7094,7 @@ class GatewayDelete(): :attr str status: (optional) The status of the request. """ - def __init__(self, *, gateway_id=None, status=None): + def __init__(self, *, gateway_id: str = None, status: str = None) -> None: """ Initialize a GatewayDelete object. @@ -6773,7 +7105,7 @@ def __init__(self, *, gateway_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GatewayDelete': """Initialize a GatewayDelete object from a json dictionary.""" args = {} valid_keys = ['gateway_id', 'status'] @@ -6788,7 +7120,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GatewayDelete 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, 'gateway_id') and self.gateway_id is not None: @@ -6797,17 +7134,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 GatewayDelete object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GatewayDelete') -> 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): + def __ne__(self, other: 'GatewayDelete') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6816,21 +7157,21 @@ class GatewayList(): """ Object containing gateways array. - :attr list[Gateway] gateways: (optional) Array of configured gateway + :attr List[Gateway] gateways: (optional) Array of configured gateway connections. """ - def __init__(self, *, gateways=None): + def __init__(self, *, gateways: List['Gateway'] = None) -> None: """ Initialize a GatewayList object. - :param list[Gateway] gateways: (optional) Array of configured gateway + :param List[Gateway] gateways: (optional) Array of configured gateway connections. """ self.gateways = gateways @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GatewayList': """Initialize a GatewayList object from a json dictionary.""" args = {} valid_keys = ['gateways'] @@ -6845,100 +7186,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GatewayList 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, 'gateways') and self.gateways is not None: _dict['gateways'] = [x._to_dict() for x in self.gateways] return _dict - def __str__(self): - """Return a `str` version of this GatewayList object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Histogram(): - """ - Histogram. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int interval: (optional) Interval of the aggregation. (For 'histogram' - type). - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - interval=None): - """ - Initialize a Histogram object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int interval: (optional) Interval of the aggregation. (For - 'histogram' type). - """ - self.field = field - self.interval = interval - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Histogram object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Histogram: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this Histogram object.""" + def __str__(self) -> str: + """Return a `str` version of this GatewayList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GatewayList') -> 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): + def __ne__(self, other: 'GatewayList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6947,42 +7221,42 @@ class HtmlSettings(): """ A list of HTML conversion settings. - :attr list[str] exclude_tags_completely: (optional) Array of HTML tags that are + :attr 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 + :attr 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 XPaths. :attr XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :attr list[str] keep_tag_attributes: (optional) An array of HTML tag attributes + :attr 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 + :attr List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ def __init__(self, *, - exclude_tags_completely=None, - exclude_tags_keep_content=None, - keep_content=None, - exclude_content=None, - keep_tag_attributes=None, - exclude_tag_attributes=None): + 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: """ Initialize a HtmlSettings object. - :param list[str] exclude_tags_completely: (optional) Array of HTML tags + :param List[str] exclude_tags_completely: (optional) Array of HTML tags that are excluded completely. - :param list[str] exclude_tags_keep_content: (optional) Array of HTML tags + :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. :param XPathPatterns keep_content: (optional) Object containing an array of XPaths. :param XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :param list[str] keep_tag_attributes: (optional) An array of HTML tag + :param List[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. - :param list[str] exclude_tag_attributes: (optional) Array of HTML tag + :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ self.exclude_tags_completely = exclude_tags_completely @@ -6993,7 +7267,7 @@ def __init__(self, self.exclude_tag_attributes = exclude_tag_attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'HtmlSettings': """Initialize a HtmlSettings object from a json dictionary.""" args = {} valid_keys = [ @@ -7024,7 +7298,12 @@ def _from_dict(cls, _dict): args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a HtmlSettings 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, 'exclude_tags_completely' @@ -7047,17 +7326,21 @@ def _to_dict(self): _dict['exclude_tag_attributes'] = self.exclude_tag_attributes return _dict - def __str__(self): + 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 HtmlSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'HtmlSettings') -> 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): + def __ne__(self, other: 'HtmlSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7074,7 +7357,11 @@ class IndexCapacity(): the environment. """ - def __init__(self, *, documents=None, disk_usage=None, collections=None): + def __init__(self, + *, + documents: 'EnvironmentDocuments' = None, + disk_usage: 'DiskUsage' = None, + collections: 'CollectionUsage' = None) -> None: """ Initialize a IndexCapacity object. @@ -7090,7 +7377,7 @@ def __init__(self, *, documents=None, disk_usage=None, collections=None): self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IndexCapacity': """Initialize a IndexCapacity object from a json dictionary.""" args = {} valid_keys = ['documents', 'disk_usage', 'collections'] @@ -7109,7 +7396,12 @@ def _from_dict(cls, _dict): _dict.get('collections')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IndexCapacity 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, 'documents') and self.documents is not None: @@ -7120,17 +7412,21 @@ def _to_dict(self): _dict['collections'] = self.collections._to_dict() return _dict - def __str__(self): + 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 IndexCapacity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IndexCapacity') -> 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): + def __ne__(self, other: 'IndexCapacity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7148,21 +7444,21 @@ 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 + :attr List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields=None): + def __init__(self, *, fields: List['Field'] = None) -> None: """ Initialize a ListCollectionFieldsResponse object. - :param list[Field] fields: (optional) An array containing information about + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ self.fields = fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} valid_keys = ['fields'] @@ -7177,24 +7473,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionFieldsResponse 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, 'fields') and self.fields is not None: _dict['fields'] = [x._to_dict() for x in self.fields] return _dict - def __str__(self): + 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 ListCollectionFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionFieldsResponse') -> 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): + def __ne__(self, other: 'ListCollectionFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7203,21 +7508,21 @@ class ListCollectionsResponse(): """ Response object containing an array of collection details. - :attr list[Collection] collections: (optional) An array containing information + :attr List[Collection] collections: (optional) An array containing information about each collection in the environment. """ - def __init__(self, *, collections=None): + def __init__(self, *, collections: List['Collection'] = None) -> None: """ Initialize a ListCollectionsResponse object. - :param list[Collection] collections: (optional) An array containing + :param List[Collection] collections: (optional) An array containing information about each collection in the environment. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -7232,24 +7537,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionsResponse') -> 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): + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7258,21 +7572,21 @@ class ListConfigurationsResponse(): """ Object containing an array of available configurations. - :attr list[Configuration] configurations: (optional) An array of configurations + :attr List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ - def __init__(self, *, configurations=None): + def __init__(self, *, configurations: List['Configuration'] = None) -> None: """ Initialize a ListConfigurationsResponse object. - :param list[Configuration] configurations: (optional) An array of + :param List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ self.configurations = configurations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} valid_keys = ['configurations'] @@ -7288,7 +7602,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListConfigurationsResponse 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, 'configurations') and self.configurations is not None: @@ -7297,17 +7616,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ListConfigurationsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListConfigurationsResponse') -> 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): + def __ne__(self, other: 'ListConfigurationsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7316,21 +7639,21 @@ class ListEnvironmentsResponse(): """ Response object containing an array of configured environments. - :attr list[Environment] environments: (optional) An array of [environments] that + :attr List[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ - def __init__(self, *, environments=None): + def __init__(self, *, environments: List['Environment'] = None) -> None: """ Initialize a ListEnvironmentsResponse object. - :param list[Environment] environments: (optional) An array of + :param List[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ self.environments = environments @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} valid_keys = ['environments'] @@ -7345,24 +7668,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListEnvironmentsResponse 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, 'environments') and self.environments is not None: _dict['environments'] = [x._to_dict() for x in self.environments] return _dict - def __str__(self): + 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 ListEnvironmentsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListEnvironmentsResponse') -> 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): + def __ne__(self, other: 'ListEnvironmentsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7372,23 +7704,26 @@ 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 + :attr List[LogQueryResponseResult] results: (optional) Array of log query response results. """ - def __init__(self, *, matching_results=None, results=None): + def __init__(self, + *, + matching_results: int = None, + results: List['LogQueryResponseResult'] = None) -> None: """ Initialize a LogQueryResponse object. :param int matching_results: (optional) Number of matching results. - :param list[LogQueryResponseResult] results: (optional) Array of log query + :param List[LogQueryResponseResult] results: (optional) Array of log query response results. """ self.matching_results = matching_results self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': """Initialize a LogQueryResponse object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'results'] @@ -7406,7 +7741,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponse 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, @@ -7416,17 +7756,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 LogQueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponse') -> 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): + def __ne__(self, other: 'LogQueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7489,20 +7833,20 @@ class LogQueryResponseResult(): def __init__(self, *, - environment_id=None, - customer_id=None, - document_type=None, - natural_language_query=None, - document_results=None, - created_timestamp=None, - client_timestamp=None, - query_id=None, - session_token=None, - collection_id=None, - display_rank=None, - document_id=None, - event_type=None, - result_type=None): + 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: """ Initialize a LogQueryResponseResult object. @@ -7574,7 +7918,7 @@ def __init__(self, self.result_type = result_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} valid_keys = [ @@ -7622,7 +7966,12 @@ def _from_dict(cls, _dict): args['result_type'] = _dict.get('result_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResult 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, 'environment_id') and self.environment_id is not None: @@ -7661,17 +8010,21 @@ def _to_dict(self): _dict['result_type'] = self.result_type return _dict - def __str__(self): + 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 LogQueryResponseResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResult') -> 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): + def __ne__(self, other: 'LogQueryResponseResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7707,17 +8060,20 @@ 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 + :attr List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. :attr int count: (optional) The number of results returned in the query associate with this log. """ - def __init__(self, *, results=None, count=None): + def __init__(self, + *, + results: List['LogQueryResponseResultDocumentsResult'] = None, + count: int = None) -> None: """ Initialize a LogQueryResponseResultDocuments object. - :param list[LogQueryResponseResultDocumentsResult] results: (optional) + :param List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. :param int count: (optional) The number of results returned in the query associate with this log. @@ -7726,7 +8082,7 @@ def __init__(self, *, results=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} valid_keys = ['results', 'count'] @@ -7744,7 +8100,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResultDocuments 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, 'results') and self.results is not None: @@ -7753,17 +8114,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 LogQueryResponseResultDocuments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResultDocuments') -> 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): + def __ne__(self, other: 'LogQueryResponseResultDocuments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7787,11 +8152,11 @@ class LogQueryResponseResultDocumentsResult(): def __init__(self, *, - position=None, - document_id=None, - score=None, - confidence=None, - collection_id=None): + position: int = None, + document_id: str = None, + score: float = None, + confidence: float = None, + collection_id: str = None) -> None: """ Initialize a LogQueryResponseResultDocumentsResult object. @@ -7813,7 +8178,7 @@ def __init__(self, self.collection_id = collection_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} valid_keys = [ @@ -7836,7 +8201,12 @@ def _from_dict(cls, _dict): args['collection_id'] = _dict.get('collection_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResultDocumentsResult 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, 'position') and self.position is not None: @@ -7851,17 +8221,21 @@ def _to_dict(self): _dict['collection_id'] = self.collection_id return _dict - def __str__(self): + 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 LogQueryResponseResultDocumentsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResultDocumentsResult') -> 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): + def __ne__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7874,11 +8248,15 @@ class MetricAggregation(): intervals are always 1 day (`1d`). :attr 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 + :attr List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ - def __init__(self, *, interval=None, event_type=None, results=None): + def __init__(self, + *, + interval: str = None, + event_type: str = None, + results: List['MetricAggregationResult'] = None) -> None: """ Initialize a MetricAggregation object. @@ -7886,7 +8264,7 @@ def __init__(self, *, interval=None, event_type=None, results=None): Metric intervals are always 1 day (`1d`). :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :param list[MetricAggregationResult] results: (optional) Array of metric + :param List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ self.interval = interval @@ -7894,7 +8272,7 @@ def __init__(self, *, interval=None, event_type=None, results=None): self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricAggregation': """Initialize a MetricAggregation object from a json dictionary.""" args = {} valid_keys = ['interval', 'event_type', 'results'] @@ -7914,7 +8292,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricAggregation 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, 'interval') and self.interval is not None: @@ -7925,17 +8308,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 MetricAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricAggregation') -> 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): + def __ne__(self, other: 'MetricAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7956,10 +8343,10 @@ class MetricAggregationResult(): def __init__(self, *, - key_as_string=None, - key=None, - matching_results=None, - event_rate=None): + key_as_string: datetime = None, + key: int = None, + matching_results: int = None, + event_rate: float = None) -> None: """ Initialize a MetricAggregationResult object. @@ -7978,7 +8365,7 @@ def __init__(self, self.event_rate = event_rate @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key_as_string', 'key', 'matching_results', 'event_rate'] @@ -7998,7 +8385,12 @@ def _from_dict(cls, _dict): args['event_rate'] = _dict.get('event_rate') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricAggregationResult 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, 'key_as_string') and self.key_as_string is not None: @@ -8012,17 +8404,21 @@ def _to_dict(self): _dict['event_rate'] = self.event_rate return _dict - def __str__(self): + 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 MetricAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricAggregationResult') -> 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): + def __ne__(self, other: 'MetricAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8031,21 +8427,22 @@ class MetricResponse(): """ The response generated from a call to a **metrics** method. - :attr list[MetricAggregation] aggregations: (optional) Array of metric + :attr List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ - def __init__(self, *, aggregations=None): + def __init__(self, *, + aggregations: List['MetricAggregation'] = None) -> None: """ Initialize a MetricResponse object. - :param list[MetricAggregation] aggregations: (optional) Array of metric + :param List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricResponse': """Initialize a MetricResponse object from a json dictionary.""" args = {} valid_keys = ['aggregations'] @@ -8061,24 +8458,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricResponse 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, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 MetricResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricResponse') -> 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): + def __ne__(self, other: 'MetricResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8089,24 +8495,27 @@ class MetricTokenAggregation(): :attr 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 + :attr List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ - def __init__(self, *, event_type=None, results=None): + def __init__(self, + *, + event_type: str = None, + results: List['MetricTokenAggregationResult'] = None) -> None: """ Initialize a MetricTokenAggregation object. :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :param list[MetricTokenAggregationResult] results: (optional) Array of + :param List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ self.event_type = event_type self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} valid_keys = ['event_type', 'results'] @@ -8124,7 +8533,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenAggregation 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, 'event_type') and self.event_type is not None: @@ -8133,17 +8547,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 MetricTokenAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenAggregation') -> 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): + def __ne__(self, other: 'MetricTokenAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8160,7 +8578,11 @@ class MetricTokenAggregationResult(): stored in the log for 30 days). """ - def __init__(self, *, key=None, matching_results=None, event_rate=None): + def __init__(self, + *, + key: str = None, + matching_results: int = None, + event_rate: float = None) -> None: """ Initialize a MetricTokenAggregationResult object. @@ -8176,7 +8598,7 @@ def __init__(self, *, key=None, matching_results=None, event_rate=None): self.event_rate = event_rate @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'event_rate'] @@ -8193,7 +8615,12 @@ def _from_dict(cls, _dict): args['event_rate'] = _dict.get('event_rate') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenAggregationResult 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, 'key') and self.key is not None: @@ -8205,17 +8632,21 @@ def _to_dict(self): _dict['event_rate'] = self.event_rate return _dict - def __str__(self): + 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 MetricTokenAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenAggregationResult') -> 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): + def __ne__(self, other: 'MetricTokenAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8224,21 +8655,22 @@ class MetricTokenResponse(): """ The response generated from a call to a **metrics** method that evaluates tokens. - :attr list[MetricTokenAggregation] aggregations: (optional) Array of metric + :attr List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ - def __init__(self, *, aggregations=None): + def __init__(self, *, + aggregations: List['MetricTokenAggregation'] = None) -> None: """ Initialize a MetricTokenResponse object. - :param list[MetricTokenAggregation] aggregations: (optional) Array of + :param List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} valid_keys = ['aggregations'] @@ -8254,104 +8686,47 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenResponse 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, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 MetricTokenResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenResponse') -> 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): + def __ne__(self, other: 'MetricTokenResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Nested(): +class NluEnrichmentCategories(): """ - Nested. + An object that indicates the Categories enrichment will be applied to the specified + field. - :attr str path: (optional) The area of the results the aggregation was - restricted to. """ - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - path=None): + def __init__(self, **kwargs) -> None: """ - Initialize a Nested object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str path: (optional) The area of the results the aggregation was - restricted to. - """ - self.path = path - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Nested object from a json dictionary.""" - args = {} - valid_keys = ['path'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Nested: ' + - ', '.join(bad_keys)) - if 'path' in _dict: - args['path'] = _dict.get('path') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - return _dict - - def __str__(self): - """Return a `str` version of this Nested object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentCategories(): - """ - An object that indicates the Categories enrichment will be applied to the specified - field. - - """ - - def __init__(self, **kwargs): - """ - Initialize a NluEnrichmentCategories object. + Initialize a NluEnrichmentCategories object. :param **kwargs: (optional) Any additional properties. """ @@ -8359,14 +8734,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentCategories': """Initialize a NluEnrichmentCategories object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentCategories 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, '_additionalProperties'): @@ -8376,7 +8756,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(NluEnrichmentCategories, @@ -8385,17 +8769,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(NluEnrichmentCategories, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this NluEnrichmentCategories object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentCategories') -> 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): + def __ne__(self, other: 'NluEnrichmentCategories') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8408,7 +8792,7 @@ class NluEnrichmentConcepts(): from each instance of the specified field. """ - def __init__(self, *, limit=None): + def __init__(self, *, limit: int = None) -> None: """ Initialize a NluEnrichmentConcepts object. @@ -8418,7 +8802,7 @@ def __init__(self, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} valid_keys = ['limit'] @@ -8431,24 +8815,33 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentConcepts 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, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentConcepts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentConcepts') -> 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): + def __ne__(self, other: 'NluEnrichmentConcepts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8459,24 +8852,25 @@ class NluEnrichmentEmotion(): :attr 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 + :attr List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a NluEnrichmentEmotion object. :param bool document: (optional) When `true`, emotion detection is performed on the entire field. - :param list[str] targets: (optional) A comma-separated list of target + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -8491,7 +8885,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentEmotion 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, 'document') and self.document is not None: @@ -8500,17 +8899,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 NluEnrichmentEmotion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentEmotion') -> 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): + def __ne__(self, other: 'NluEnrichmentEmotion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8539,13 +8942,13 @@ class NluEnrichmentEntities(): def __init__(self, *, - sentiment=None, - emotion=None, - limit=None, - mentions=None, - mention_types=None, - sentence_locations=None, - model=None): + sentiment: bool = None, + emotion: bool = None, + limit: int = None, + mentions: bool = None, + mention_types: bool = None, + sentence_locations: bool = None, + model: str = None) -> None: """ Initialize a NluEnrichmentEntities object. @@ -8575,7 +8978,7 @@ def __init__(self, self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} valid_keys = [ @@ -8603,7 +9006,12 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentEntities 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, 'sentiment') and self.sentiment is not None: @@ -8624,17 +9032,21 @@ def _to_dict(self): _dict['model'] = self.model return _dict - def __str__(self): + 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 NluEnrichmentEntities object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentEntities') -> 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): + def __ne__(self, other: 'NluEnrichmentEntities') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8663,14 +9075,14 @@ class NluEnrichmentFeatures(): def __init__(self, *, - keywords=None, - entities=None, - sentiment=None, - emotion=None, - categories=None, - semantic_roles=None, - relations=None, - concepts=None): + keywords: 'NluEnrichmentKeywords' = None, + entities: 'NluEnrichmentEntities' = None, + sentiment: 'NluEnrichmentSentiment' = None, + emotion: 'NluEnrichmentEmotion' = None, + categories: 'NluEnrichmentCategories' = None, + semantic_roles: 'NluEnrichmentSemanticRoles' = None, + relations: 'NluEnrichmentRelations' = None, + concepts: 'NluEnrichmentConcepts' = None) -> None: """ Initialize a NluEnrichmentFeatures object. @@ -8701,7 +9113,7 @@ def __init__(self, self.concepts = concepts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} valid_keys = [ @@ -8739,7 +9151,12 @@ def _from_dict(cls, _dict): _dict.get('concepts')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentFeatures 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, 'keywords') and self.keywords is not None: @@ -8760,17 +9177,21 @@ def _to_dict(self): _dict['concepts'] = self.concepts._to_dict() return _dict - def __str__(self): + 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 NluEnrichmentFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentFeatures') -> 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): + def __ne__(self, other: 'NluEnrichmentFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8787,7 +9208,11 @@ class NluEnrichmentKeywords(): instance of the specified field. """ - def __init__(self, *, sentiment=None, emotion=None, limit=None): + def __init__(self, + *, + sentiment: bool = None, + emotion: bool = None, + limit: int = None) -> None: """ Initialize a NluEnrichmentKeywords object. @@ -8803,7 +9228,7 @@ def __init__(self, *, sentiment=None, emotion=None, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} valid_keys = ['sentiment', 'emotion', 'limit'] @@ -8820,7 +9245,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentKeywords 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, 'sentiment') and self.sentiment is not None: @@ -8831,17 +9261,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentKeywords object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentKeywords') -> 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): + def __ne__(self, other: 'NluEnrichmentKeywords') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8856,7 +9290,7 @@ class NluEnrichmentRelations(): model is`en-news`. """ - def __init__(self, *, model=None): + def __init__(self, *, model: str = None) -> None: """ Initialize a NluEnrichmentRelations object. @@ -8868,7 +9302,7 @@ def __init__(self, *, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} valid_keys = ['model'] @@ -8881,24 +9315,33 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentRelations 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, 'model') and self.model is not None: _dict['model'] = self.model return _dict - def __str__(self): + 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 NluEnrichmentRelations object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentRelations') -> 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): + def __ne__(self, other: 'NluEnrichmentRelations') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8915,7 +9358,11 @@ class NluEnrichmentSemanticRoles(): extact from each instance of the specified field. """ - def __init__(self, *, entities=None, keywords=None, limit=None): + def __init__(self, + *, + entities: bool = None, + keywords: bool = None, + limit: int = None) -> None: """ Initialize a NluEnrichmentSemanticRoles object. @@ -8931,7 +9378,7 @@ def __init__(self, *, entities=None, keywords=None, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} valid_keys = ['entities', 'keywords', 'limit'] @@ -8948,7 +9395,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentSemanticRoles 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, 'entities') and self.entities is not None: @@ -8959,17 +9411,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentSemanticRoles object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentSemanticRoles') -> 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): + def __ne__(self, other: 'NluEnrichmentSemanticRoles') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8980,24 +9436,25 @@ class NluEnrichmentSentiment(): :attr 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 + :attr List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a NluEnrichmentSentiment object. :param bool document: (optional) When `true`, sentiment analysis is performed on the entire field. - :param list[str] targets: (optional) A comma-separated list of target + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -9012,7 +9469,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentSentiment 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, 'document') and self.document is not None: @@ -9021,17 +9483,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 NluEnrichmentSentiment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentSentiment') -> 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): + def __ne__(self, other: 'NluEnrichmentSentiment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9071,9 +9537,9 @@ class NormalizationOperation(): def __init__(self, *, - operation=None, - source_field=None, - destination_field=None): + operation: str = None, + source_field: str = None, + destination_field: str = None) -> None: """ Initialize a NormalizationOperation object. @@ -9113,7 +9579,7 @@ def __init__(self, self.destination_field = destination_field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': """Initialize a NormalizationOperation object from a json dictionary.""" args = {} valid_keys = ['operation', 'source_field', 'destination_field'] @@ -9130,7 +9596,12 @@ def _from_dict(cls, _dict): args['destination_field'] = _dict.get('destination_field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NormalizationOperation 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, 'operation') and self.operation is not None: @@ -9142,17 +9613,21 @@ def _to_dict(self): _dict['destination_field'] = self.destination_field return _dict - def __str__(self): + 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 NormalizationOperation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NormalizationOperation') -> 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): + def __ne__(self, other: 'NormalizationOperation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9223,13 +9698,13 @@ class Notice(): def __init__(self, *, - notice_id=None, - created=None, - document_id=None, - query_id=None, - severity=None, - step=None, - description=None): + 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: """ Initialize a Notice object. @@ -9268,7 +9743,7 @@ def __init__(self, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} valid_keys = [ @@ -9296,7 +9771,12 @@ def _from_dict(cls, _dict): args['description'] = _dict.get('description') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice 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, 'notice_id') and self.notice_id is not None: @@ -9315,17 +9795,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Notice') -> 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): + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9341,20 +9825,20 @@ class PdfHeadingDetection(): """ Object containing heading detection conversion settings for PDF documents. - :attr list[FontSetting] fonts: (optional) Array of font matching configurations. + :attr List[FontSetting] fonts: (optional) Array of font matching configurations. """ - def __init__(self, *, fonts=None): + def __init__(self, *, fonts: List['FontSetting'] = None) -> None: """ Initialize a PdfHeadingDetection object. - :param list[FontSetting] fonts: (optional) Array of font matching + :param List[FontSetting] fonts: (optional) Array of font matching configurations. """ self.fonts = fonts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} valid_keys = ['fonts'] @@ -9369,24 +9853,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PdfHeadingDetection 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, 'fonts') and self.fonts is not None: _dict['fonts'] = [x._to_dict() for x in self.fonts] return _dict - def __str__(self): + 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 PdfHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PdfHeadingDetection') -> 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): + def __ne__(self, other: 'PdfHeadingDetection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9399,7 +9892,7 @@ class PdfSettings(): detection conversion settings for PDF documents. """ - def __init__(self, *, heading=None): + def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: """ Initialize a PdfSettings object. @@ -9409,7 +9902,7 @@ def __init__(self, *, heading=None): self.heading = heading @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PdfSettings': """Initialize a PdfSettings object from a json dictionary.""" args = {} valid_keys = ['heading'] @@ -9423,24 +9916,33 @@ def _from_dict(cls, _dict): _dict.get('heading')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PdfSettings 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, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict - def __str__(self): + 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 PdfSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PdfSettings') -> 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): + def __ne__(self, other: 'PdfSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9451,27 +9953,27 @@ class QueryAggregation(): :attr str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. - :attr list[AggregationResult] results: (optional) Array of aggregation results. + :attr List[AggregationResult] results: (optional) Array of aggregation results. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryAggregation] aggregations: (optional) Aggregations returned by + :attr List[QueryAggregation] aggregations: (optional) Aggregations returned by Discovery. """ def __init__(self, *, - type=None, - results=None, - matching_results=None, - aggregations=None): + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryAggregation object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation + :param List[AggregationResult] results: (optional) Array of aggregation results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations + :param List[QueryAggregation] aggregations: (optional) Aggregations returned by Discovery. """ self.type = type @@ -9480,8 +9982,11 @@ def __init__(self, self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryAggregation': """Initialize a QueryAggregation object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) args = {} valid_keys = ['type', 'results', 'matching_results', 'aggregations'] bad_keys = set(_dict.keys()) - set(valid_keys) @@ -9504,7 +10009,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregation 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, 'type') and self.type is not None: @@ -9518,31 +10028,63 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 QueryAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryAggregation') -> 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): + def __ne__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['histogram'] = 'Histogram' + mapping['max'] = 'Calculation' + mapping['min'] = 'Calculation' + mapping['average'] = 'Calculation' + mapping['sum'] = 'Calculation' + mapping['unique_count'] = 'Calculation' + mapping['term'] = 'Term' + mapping['filter'] = 'Filter' + mapping['nested'] = 'Nested' + mapping['timeslice'] = 'Timeslice' + mapping['top_hits'] = 'TopHits' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in QueryAggregation JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + 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 + :attr List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + :attr List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :attr list[QueryPassages] passages: (optional) Array of passage results that + :attr List[QueryPassages] passages: (optional) Array of passage results that match the query. :attr int duplicates_removed: (optional) The number of duplicates removed from this notices query. @@ -9550,20 +10092,20 @@ class QueryNoticesResponse(): def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - passages=None, - duplicates_removed=None): + matching_results: int = None, + results: List['QueryNoticesResult'] = None, + aggregations: List['QueryAggregation'] = None, + passages: List['QueryPassages'] = None, + duplicates_removed: int = None) -> None: """ Initialize a QueryNoticesResponse object. :param int matching_results: (optional) The number of matching results. - :param list[QueryNoticesResult] results: (optional) Array of document + :param List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :param list[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :param list[QueryPassages] passages: (optional) Array of passage results + :param List[QueryPassages] passages: (optional) Array of passage results that match the query. :param int duplicates_removed: (optional) The number of duplicates removed from this notices query. @@ -9575,7 +10117,7 @@ def __init__(self, self.duplicates_removed = duplicates_removed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -9606,7 +10148,12 @@ def _from_dict(cls, _dict): args['duplicates_removed'] = _dict.get('duplicates_removed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResponse 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, @@ -9624,17 +10171,21 @@ def _to_dict(self): _dict['duplicates_removed'] = self.duplicates_removed return _dict - def __str__(self): + 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 QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResponse') -> 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): + def __ne__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9655,21 +10206,21 @@ class QueryNoticesResult(): :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. + :attr List[Notice] notices: (optional) Array of notices for the document. """ def __init__(self, *, - id=None, - metadata=None, - collection_id=None, - result_metadata=None, - code=None, - filename=None, - file_type=None, - sha1=None, - notices=None, - **kwargs): + 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: """ Initialize a QueryNoticesResult object. @@ -9687,7 +10238,7 @@ def __init__(self, :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. + :param List[Notice] notices: (optional) Array of notices for the document. :param **kwargs: (optional) Any additional properties. """ self.id = id @@ -9703,7 +10254,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -9740,7 +10291,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResult 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: @@ -9769,7 +10325,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'id', 'metadata', 'collection_id', 'result_metadata', 'code', 'filename', 'file_type', 'sha1', 'notices' @@ -9781,17 +10341,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryNoticesResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryNoticesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResult') -> 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): + def __ne__(self, other: 'QueryNoticesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9824,12 +10384,12 @@ class QueryPassages(): def __init__(self, *, - document_id=None, - passage_score=None, - passage_text=None, - start_offset=None, - end_offset=None, - field=None): + document_id: str = None, + passage_score: float = None, + passage_text: str = None, + start_offset: int = None, + end_offset: int = None, + field: str = None) -> None: """ Initialize a QueryPassages object. @@ -9853,7 +10413,7 @@ def __init__(self, self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryPassages': """Initialize a QueryPassages object from a json dictionary.""" args = {} valid_keys = [ @@ -9879,7 +10439,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryPassages 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, 'document_id') and self.document_id is not None: @@ -9896,17 +10461,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 QueryPassages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryPassages') -> 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): + def __ne__(self, other: 'QueryPassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9917,11 +10486,11 @@ class QueryResponse(): :attr int matching_results: (optional) The number of matching results for the query. - :attr list[QueryResult] results: (optional) Array of document results for the + :attr List[QueryResult] results: (optional) Array of document results for the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + :attr List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :attr list[QueryPassages] passages: (optional) Array of passage results for the + :attr List[QueryPassages] passages: (optional) Array of passage results for the query. :attr int duplicates_removed: (optional) The number of duplicate results removed. @@ -9937,24 +10506,24 @@ class QueryResponse(): def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - passages=None, - duplicates_removed=None, - session_token=None, - retrieval_details=None, - suggested_query=None): + 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: """ Initialize a QueryResponse object. :param int matching_results: (optional) The number of matching results for the query. - :param list[QueryResult] results: (optional) Array of document results for + :param List[QueryResult] results: (optional) Array of document results for the query. - :param list[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :param list[QueryPassages] passages: (optional) Array of passage results + :param List[QueryPassages] passages: (optional) Array of passage results for the query. :param int duplicates_removed: (optional) The number of duplicate results removed. @@ -9977,7 +10546,7 @@ def __init__(self, self.suggested_query = suggested_query @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -10016,7 +10585,12 @@ def _from_dict(cls, _dict): args['suggested_query'] = _dict.get('suggested_query') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponse 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, @@ -10042,17 +10616,21 @@ def _to_dict(self): _dict['suggested_query'] = self.suggested_query return _dict - def __str__(self): + 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 QueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResponse') -> 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): + def __ne__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10071,11 +10649,11 @@ class QueryResult(): def __init__(self, *, - id=None, - metadata=None, - collection_id=None, - result_metadata=None, - **kwargs): + id: str = None, + metadata: dict = None, + collection_id: str = None, + result_metadata: 'QueryResultMetadata' = None, + **kwargs) -> None: """ Initialize a QueryResult object. @@ -10095,7 +10673,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -10115,7 +10693,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResult 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: @@ -10134,7 +10717,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'id', 'metadata', 'collection_id', 'result_metadata'} if not hasattr(self, '_additionalProperties'): super(QueryResult, self).__setattr__('_additionalProperties', set()) @@ -10142,17 +10729,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResult') -> 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): + def __ne__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10171,7 +10758,7 @@ class QueryResultMetadata(): specified in the `document_retrieval_strategy` field of the result set. """ - def __init__(self, score, *, confidence=None): + def __init__(self, score: float, *, confidence: float = None) -> None: """ Initialize a QueryResultMetadata object. @@ -10189,7 +10776,7 @@ def __init__(self, score, *, confidence=None): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} valid_keys = ['score', 'confidence'] @@ -10208,7 +10795,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultMetadata 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, 'score') and self.score is not None: @@ -10217,17 +10809,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 QueryResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultMetadata') -> 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): + def __ne__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10247,7 +10843,7 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy=None): + def __init__(self, *, document_retrieval_strategy: str = None) -> None: """ Initialize a RetrievalDetails object. @@ -10265,7 +10861,7 @@ def __init__(self, *, document_retrieval_strategy=None): self.document_retrieval_strategy = document_retrieval_strategy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} valid_keys = ['document_retrieval_strategy'] @@ -10279,7 +10875,12 @@ def _from_dict(cls, _dict): 'document_retrieval_strategy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' @@ -10288,17 +10889,21 @@ def _to_dict(self): 'document_retrieval_strategy'] = self.document_retrieval_strategy return _dict - def __str__(self): + 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 RetrievalDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RetrievalDetails') -> 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): + def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10348,11 +10953,11 @@ class SduStatus(): def __init__(self, *, - enabled=None, - total_annotated_pages=None, - total_pages=None, - total_documents=None, - custom_fields=None): + enabled: bool = None, + total_annotated_pages: int = None, + total_pages: int = None, + total_documents: int = None, + custom_fields: 'SduStatusCustomFields' = None) -> None: """ Initialize a SduStatus object. @@ -10385,7 +10990,7 @@ def __init__(self, self.custom_fields = custom_fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SduStatus': """Initialize a SduStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -10410,7 +11015,12 @@ def _from_dict(cls, _dict): _dict.get('custom_fields')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SduStatus 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, 'enabled') and self.enabled is not None: @@ -10427,17 +11037,21 @@ def _to_dict(self): _dict['custom_fields'] = self.custom_fields._to_dict() return _dict - def __str__(self): + 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 SduStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SduStatus') -> 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): + def __ne__(self, other: 'SduStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10453,7 +11067,8 @@ class SduStatusCustomFields(): are allowed in this collection. """ - def __init__(self, *, defined=None, maximum_allowed=None): + def __init__(self, *, defined: int = None, + maximum_allowed: int = None) -> None: """ Initialize a SduStatusCustomFields object. @@ -10466,7 +11081,7 @@ def __init__(self, *, defined=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} valid_keys = ['defined', 'maximum_allowed'] @@ -10481,9 +11096,14 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a SduStatusCustomFields 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, 'defined') and self.defined is not None: _dict['defined'] = self.defined if hasattr(self, @@ -10491,17 +11111,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 SduStatusCustomFields object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SduStatusCustomFields') -> 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): + def __ne__(self, other: 'SduStatusCustomFields') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10522,10 +11146,10 @@ class SearchStatus(): def __init__(self, *, - scope=None, - status=None, - status_description=None, - last_trained=None): + scope: str = None, + status: str = None, + status_description: str = None, + last_trained: date = None) -> None: """ Initialize a SearchStatus object. @@ -10544,7 +11168,7 @@ def __init__(self, self.last_trained = last_trained @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchStatus': """Initialize a SearchStatus object from a json dictionary.""" args = {} valid_keys = ['scope', 'status', 'status_description', 'last_trained'] @@ -10563,7 +11187,12 @@ def _from_dict(cls, _dict): args['last_trained'] = _dict.get('last_trained') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchStatus 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, 'scope') and self.scope is not None: @@ -10578,17 +11207,21 @@ def _to_dict(self): _dict['last_trained'] = self.last_trained return _dict - def __str__(self): + 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 SearchStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchStatus') -> 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): + def __ne__(self, other: 'SearchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10609,12 +11242,12 @@ class SegmentSettings(): :attr bool enabled: (optional) Enables/disables the Document Segmentation feature. - :attr list[str] selector_tags: (optional) Defines the heading level that splits + :attr 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 + :attr 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, @@ -10628,21 +11261,21 @@ class SegmentSettings(): def __init__(self, *, - enabled=None, - selector_tags=None, - annotated_fields=None): + enabled: bool = None, + selector_tags: List[str] = None, + annotated_fields: List[str] = None) -> None: """ Initialize a SegmentSettings object. :param bool enabled: (optional) Enables/disables the Document Segmentation feature. - :param list[str] selector_tags: (optional) Defines the heading level that + :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. - :param 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 @@ -10659,7 +11292,7 @@ def __init__(self, self.annotated_fields = annotated_fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SegmentSettings': """Initialize a SegmentSettings object from a json dictionary.""" args = {} valid_keys = ['enabled', 'selector_tags', 'annotated_fields'] @@ -10676,7 +11309,12 @@ def _from_dict(cls, _dict): args['annotated_fields'] = _dict.get('annotated_fields') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SegmentSettings 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, 'enabled') and self.enabled is not None: @@ -10688,17 +11326,21 @@ def _to_dict(self): _dict['annotated_fields'] = self.annotated_fields return _dict - def __str__(self): + 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 SegmentSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SegmentSettings') -> 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): + def __ne__(self, other: 'SegmentSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10728,10 +11370,10 @@ class Source(): def __init__(self, *, - type=None, - credential_id=None, - schedule=None, - options=None): + type: str = None, + credential_id: str = None, + schedule: 'SourceSchedule' = None, + options: 'SourceOptions' = None) -> None: """ Initialize a Source object. @@ -10759,7 +11401,7 @@ def __init__(self, self.options = options @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Source': """Initialize a Source object from a json dictionary.""" args = {} valid_keys = ['type', 'credential_id', 'schedule', 'options'] @@ -10778,7 +11420,12 @@ def _from_dict(cls, _dict): args['options'] = SourceOptions._from_dict(_dict.get('options')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Source 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, 'type') and self.type is not None: @@ -10791,17 +11438,21 @@ def _to_dict(self): _dict['options'] = self.options._to_dict() return _dict - def __str__(self): + 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 Source object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Source') -> 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): + def __ne__(self, other: 'Source') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10827,20 +11478,20 @@ class SourceOptions(): """ The **options** object defines which items to crawl from the source system. - :attr list[SourceOptionsFolder] folders: (optional) Array of folders to crawl + :attr 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 + :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 + :attr 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 + :attr 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 + :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 **crawl_all_buckets** field is `false` or not specified. @@ -10851,30 +11502,30 @@ class SourceOptions(): def __init__(self, *, - folders=None, - objects=None, - site_collections=None, - urls=None, - buckets=None, - crawl_all_buckets=None): + 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: """ Initialize a SourceOptions object. - :param list[SourceOptionsFolder] folders: (optional) Array of folders to + :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`. - :param list[SourceOptionsObject] objects: (optional) Array of Salesforce + :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 + :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`. - :param list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs + :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`. - :param list[SourceOptionsBuckets] buckets: (optional) Array of cloud object + :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. @@ -10890,7 +11541,7 @@ def __init__(self, self.crawl_all_buckets = crawl_all_buckets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptions': """Initialize a SourceOptions object from a json dictionary.""" args = {} valid_keys = [ @@ -10930,7 +11581,12 @@ def _from_dict(cls, _dict): args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptions 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, 'folders') and self.folders is not None: @@ -10951,17 +11607,21 @@ def _to_dict(self): _dict['crawl_all_buckets'] = self.crawl_all_buckets return _dict - def __str__(self): + 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 SourceOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptions') -> 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): + def __ne__(self, other: 'SourceOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10975,7 +11635,7 @@ class SourceOptionsBuckets(): object store bucket. If not specified, all documents in the bucket are crawled. """ - def __init__(self, name, *, limit=None): + def __init__(self, name: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsBuckets object. @@ -10988,7 +11648,7 @@ def __init__(self, name, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} valid_keys = ['name', 'limit'] @@ -11007,7 +11667,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsBuckets 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: @@ -11016,17 +11681,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsBuckets object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsBuckets') -> 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): + def __ne__(self, other: 'SourceOptionsBuckets') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11042,7 +11711,8 @@ class SourceOptionsFolder(): folder. By default, all documents in the folder are crawled. """ - def __init__(self, owner_user_id, folder_id, *, limit=None): + def __init__(self, owner_user_id: str, folder_id: str, *, + limit: int = None) -> None: """ Initialize a SourceOptionsFolder object. @@ -11057,7 +11727,7 @@ def __init__(self, owner_user_id, folder_id, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} valid_keys = ['owner_user_id', 'folder_id', 'limit'] @@ -11082,7 +11752,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsFolder 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, 'owner_user_id') and self.owner_user_id is not None: @@ -11093,17 +11768,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsFolder object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsFolder') -> 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): + def __ne__(self, other: 'SourceOptionsFolder') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11118,7 +11797,7 @@ class SourceOptionsObject(): document object. By default, all documents in the document object are crawled. """ - def __init__(self, name, *, limit=None): + def __init__(self, name: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsObject object. @@ -11132,7 +11811,7 @@ def __init__(self, name, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} valid_keys = ['name', 'limit'] @@ -11151,7 +11830,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsObject 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: @@ -11160,17 +11844,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsObject') -> 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): + def __ne__(self, other: 'SourceOptionsObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11187,7 +11875,7 @@ class SourceOptionsSiteColl(): site collection. By default, all documents in the site collection are crawled. """ - def __init__(self, site_collection_path, *, limit=None): + def __init__(self, site_collection_path: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsSiteColl object. @@ -11203,7 +11891,7 @@ def __init__(self, site_collection_path, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} valid_keys = ['site_collection_path', 'limit'] @@ -11222,7 +11910,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsSiteColl 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, 'site_collection_path' @@ -11232,17 +11925,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsSiteColl object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsSiteColl') -> 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): + def __ne__(self, other: 'SourceOptionsSiteColl') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11272,22 +11969,22 @@ class SourceOptionsWebCrawl(): 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 + :attr 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, + url: str, *, - limit_to_starting_hosts=None, - crawl_speed=None, - allow_untrusted_certificate=None, - maximum_hops=None, - request_timeout=None, - override_robots_txt=None, - blacklist=None): + 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: """ Initialize a SourceOptionsWebCrawl object. @@ -11313,7 +12010,7 @@ def __init__(self, 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**. - :param 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`. @@ -11328,7 +12025,7 @@ def __init__(self, self.blacklist = blacklist @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} valid_keys = [ @@ -11365,7 +12062,12 @@ def _from_dict(cls, _dict): args['blacklist'] = _dict.get('blacklist') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsWebCrawl 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, 'url') and self.url is not None: @@ -11392,17 +12094,21 @@ def _to_dict(self): _dict['blacklist'] = self.blacklist return _dict - def __str__(self): + 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 SourceOptionsWebCrawl object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsWebCrawl') -> 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): + def __ne__(self, other: 'SourceOptionsWebCrawl') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11440,7 +12146,11 @@ class SourceSchedule(): 06:00. """ - def __init__(self, *, enabled=None, time_zone=None, frequency=None): + def __init__(self, + *, + enabled: bool = None, + time_zone: str = None, + frequency: str = None) -> None: """ Initialize a SourceSchedule object. @@ -11465,7 +12175,7 @@ def __init__(self, *, enabled=None, time_zone=None, frequency=None): self.frequency = frequency @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceSchedule': """Initialize a SourceSchedule object from a json dictionary.""" args = {} valid_keys = ['enabled', 'time_zone', 'frequency'] @@ -11482,7 +12192,12 @@ def _from_dict(cls, _dict): args['frequency'] = _dict.get('frequency') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceSchedule 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, 'enabled') and self.enabled is not None: @@ -11493,17 +12208,21 @@ def _to_dict(self): _dict['frequency'] = self.frequency return _dict - def __str__(self): + 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 SourceSchedule object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceSchedule') -> 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): + def __ne__(self, other: 'SourceSchedule') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11539,7 +12258,8 @@ class SourceStatus(): time of the next crawl attempt. """ - def __init__(self, *, status=None, next_crawl=None): + def __init__(self, *, status: str = None, + next_crawl: datetime = None) -> None: """ Initialize a SourceStatus object. @@ -11559,7 +12279,7 @@ def __init__(self, *, status=None, next_crawl=None): self.next_crawl = next_crawl @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceStatus': """Initialize a SourceStatus object from a json dictionary.""" args = {} valid_keys = ['status', 'next_crawl'] @@ -11574,7 +12294,12 @@ def _from_dict(cls, _dict): args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceStatus 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, 'status') and self.status is not None: @@ -11583,17 +12308,21 @@ def _to_dict(self): _dict['next_crawl'] = datetime_to_string(self.next_crawl) return _dict - def __str__(self): + 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 SourceStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceStatus') -> 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): + def __ne__(self, other: 'SourceStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11615,193 +12344,34 @@ class StatusEnum(Enum): UNKNOWN = "unknown" -class Term(): - """ - Term. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int count: (optional) The number of terms identified. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - count=None): - """ - Initialize a Term object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int count: (optional) The number of terms identified. - """ - self.field = field - self.count = count - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Term object from a json dictionary.""" - args = {} - valid_keys = ['field', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Term: ' + - ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'count' in _dict: - args['count'] = _dict.get('count') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - return _dict - - def __str__(self): - """Return a `str` version of this Term object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Timeslice(): - """ - Timeslice. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr str interval: (optional) Interval of the aggregation. Valid date interval - values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, - month/months, and year/years. - :attr bool anomaly: (optional) Used to indicate that anomaly detection should be - performed. Anomaly detection is used to locate unusual datapoints within a time - series. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - interval=None, - anomaly=None): - """ - Initialize a Timeslice object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param str interval: (optional) Interval of the aggregation. Valid date - interval values are second/seconds minute/minutes, hour/hours, day/days, - week/weeks, month/months, and year/years. - :param bool anomaly: (optional) Used to indicate that anomaly detection - should be performed. Anomaly detection is used to locate unusual datapoints - within a time series. - """ - self.field = field - self.interval = interval - self.anomaly = anomaly - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Timeslice object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'anomaly'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Timeslice: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - if 'anomaly' in _dict: - args['anomaly'] = _dict.get('anomaly') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'anomaly') and self.anomaly is not None: - _dict['anomaly'] = self.anomaly - return _dict - - def __str__(self): - """Return a `str` version of this Timeslice object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - 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 + :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 + :attr 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. For example `noun`. Custom parts of speech can be specified. """ - def __init__(self, text, tokens, part_of_speech, *, readings=None): + def __init__(self, + text: str, + tokens: List[str], + part_of_speech: str, + *, + readings: List[str] = None) -> None: """ Initialize a TokenDictRule object. :param str text: The string to tokenize. - :param list[str] tokens: Array of tokens that the `text` field is split + :param List[str] tokens: Array of tokens that the `text` field is split into when found. :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. - :param list[str] readings: (optional) Array of tokens that represent the + :param List[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. """ self.text = text @@ -11810,7 +12380,7 @@ def __init__(self, text, tokens, part_of_speech, *, readings=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenDictRule': """Initialize a TokenDictRule object from a json dictionary.""" args = {} valid_keys = ['text', 'tokens', 'readings', 'part_of_speech'] @@ -11840,7 +12410,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenDictRule 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: @@ -11853,17 +12428,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): - """Return a `str` version of this TokenDictRule object.""" + 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 TokenDictRule object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenDictRule') -> 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): + def __ne__(self, other: 'TokenDictRule') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11878,7 +12457,7 @@ class TokenDictStatusResponse(): `tokenization_dictionary` or `stopwords`. """ - def __init__(self, *, status=None, type=None): + def __init__(self, *, status: str = None, type: str = None) -> None: """ Initialize a TokenDictStatusResponse object. @@ -11891,7 +12470,7 @@ def __init__(self, *, status=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} valid_keys = ['status', 'type'] @@ -11906,7 +12485,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenDictStatusResponse 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, 'status') and self.status is not None: @@ -11915,17 +12499,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 TokenDictStatusResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenDictStatusResponse') -> 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): + def __ne__(self, other: 'TokenDictStatusResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11938,100 +12526,31 @@ class StatusEnum(Enum): NOT_FOUND = "not found" -class TopHits(): - """ - TopHits. - - :attr int size: (optional) Number of top hits returned by the aggregation. - :attr TopHitsResults hits: (optional) - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - size=None, - hits=None): - """ - Initialize a TopHits object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param int size: (optional) Number of top hits returned by the aggregation. - :param TopHitsResults hits: (optional) - """ - self.size = size - self.hits = hits - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TopHits object from a json dictionary.""" - args = {} - valid_keys = ['size', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TopHits: ' + - ', '.join(bad_keys)) - if 'size' in _dict: - args['size'] = _dict.get('size') - if 'hits' in _dict: - args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this TopHits object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TopHitsResults(): """ Top hit information for this query. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryResult] hits: (optional) Top results returned by the + :attr List[QueryResult] hits: (optional) Top results returned by the aggregation. """ - def __init__(self, *, matching_results=None, hits=None): + def __init__(self, + *, + matching_results: int = None, + hits: List['QueryResult'] = None) -> None: """ Initialize a TopHitsResults object. :param int matching_results: (optional) Number of matching results. - :param list[QueryResult] hits: (optional) Top results returned by the + :param List[QueryResult] hits: (optional) Top results returned by the aggregation. """ self.matching_results = matching_results self.hits = hits @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TopHitsResults': """Initialize a TopHitsResults object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'hits'] @@ -12048,7 +12567,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TopHitsResults 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, @@ -12058,17 +12582,21 @@ def _to_dict(self): _dict['hits'] = [x._to_dict() for x in self.hits] return _dict - def __str__(self): + 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 TopHitsResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TopHitsResults') -> 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): + def __ne__(self, other: 'TopHitsResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12081,11 +12609,14 @@ class TrainingDataSet(): training data set. :attr str collection_id: (optional) The collection id associated with this training data set. - :attr list[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. """ - def __init__(self, *, environment_id=None, collection_id=None, - queries=None): + def __init__(self, + *, + environment_id: str = None, + collection_id: str = None, + queries: List['TrainingQuery'] = None) -> None: """ Initialize a TrainingDataSet object. @@ -12093,14 +12624,14 @@ def __init__(self, *, environment_id=None, collection_id=None, this training data set. :param str collection_id: (optional) The collection id associated with this training data set. - :param list[TrainingQuery] queries: (optional) Array of training queries. + :param List[TrainingQuery] queries: (optional) Array of training queries. """ self.environment_id = environment_id self.collection_id = collection_id self.queries = queries @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': """Initialize a TrainingDataSet object from a json dictionary.""" args = {} valid_keys = ['environment_id', 'collection_id', 'queries'] @@ -12119,7 +12650,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataSet 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, 'environment_id') and self.environment_id is not None: @@ -12130,17 +12666,21 @@ def _to_dict(self): _dict['queries'] = [x._to_dict() for x in self.queries] return _dict - def __str__(self): + 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 TrainingDataSet object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataSet') -> 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): + def __ne__(self, other: 'TrainingDataSet') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12158,9 +12698,9 @@ class TrainingExample(): def __init__(self, *, - document_id=None, - cross_reference=None, - relevance=None): + document_id: str = None, + cross_reference: str = None, + relevance: int = None) -> None: """ Initialize a TrainingExample object. @@ -12175,7 +12715,7 @@ def __init__(self, self.relevance = relevance @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} valid_keys = ['document_id', 'cross_reference', 'relevance'] @@ -12192,7 +12732,12 @@ def _from_dict(cls, _dict): args['relevance'] = _dict.get('relevance') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExample 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, 'document_id') and self.document_id is not None: @@ -12204,17 +12749,21 @@ def _to_dict(self): _dict['relevance'] = self.relevance return _dict - def __str__(self): + 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 TrainingExample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExample') -> 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): + def __ne__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12223,20 +12772,20 @@ class TrainingExampleList(): """ Object containing an array of training examples. - :attr list[TrainingExample] examples: (optional) Array of training examples. + :attr List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, *, examples=None): + def __init__(self, *, examples: List['TrainingExample'] = None) -> None: """ Initialize a TrainingExampleList object. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. """ self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': """Initialize a TrainingExampleList object from a json dictionary.""" args = {} valid_keys = ['examples'] @@ -12251,24 +12800,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExampleList 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, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingExampleList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExampleList') -> 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): + def __ne__(self, other: 'TrainingExampleList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12282,15 +12840,15 @@ class TrainingQuery(): training query. :attr 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. + :attr List[TrainingExample] examples: (optional) Array of training examples. """ def __init__(self, *, - query_id=None, - natural_language_query=None, - filter=None, - examples=None): + query_id: str = None, + natural_language_query: str = None, + filter: str = None, + examples: List['TrainingExample'] = None) -> None: """ Initialize a TrainingQuery object. @@ -12300,7 +12858,7 @@ def __init__(self, the training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. """ self.query_id = query_id @@ -12309,7 +12867,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} valid_keys = [ @@ -12332,7 +12890,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuery 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, 'query_id') and self.query_id is not None: @@ -12346,17 +12909,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingQuery object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuery') -> 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): + def __ne__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12387,15 +12954,15 @@ class TrainingStatus(): def __init__(self, *, - total_examples=None, - available=None, - processing=None, - minimum_queries_added=None, - minimum_examples_added=None, - sufficient_label_diversity=None, - notices=None, - successfully_trained=None, - data_updated=None): + 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: """ Initialize a TrainingStatus object. @@ -12430,7 +12997,7 @@ def __init__(self, self.data_updated = data_updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -12466,7 +13033,12 @@ def _from_dict(cls, _dict): args['data_updated'] = string_to_datetime(_dict.get('data_updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingStatus 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, 'total_examples') and self.total_examples is not None: @@ -12495,17 +13067,21 @@ def _to_dict(self): _dict['data_updated'] = datetime_to_string(self.data_updated) return _dict - def __str__(self): + 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 TrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingStatus') -> 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): + def __ne__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12514,25 +13090,28 @@ 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 + :attr List[FontSetting] fonts: (optional) Array of font matching configurations. + :attr List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ - def __init__(self, *, fonts=None, styles=None): + def __init__(self, + *, + fonts: List['FontSetting'] = None, + styles: List['WordStyle'] = None) -> None: """ Initialize a WordHeadingDetection object. - :param list[FontSetting] fonts: (optional) Array of font matching + :param List[FontSetting] fonts: (optional) Array of font matching configurations. - :param list[WordStyle] styles: (optional) Array of Microsoft Word styles to + :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ self.fonts = fonts self.styles = styles @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} valid_keys = ['fonts', 'styles'] @@ -12551,7 +13130,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordHeadingDetection 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, 'fonts') and self.fonts is not None: @@ -12560,17 +13144,21 @@ def _to_dict(self): _dict['styles'] = [x._to_dict() for x in self.styles] return _dict - def __str__(self): + 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 WordHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordHeadingDetection') -> 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): + def __ne__(self, other: 'WordHeadingDetection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12583,7 +13171,7 @@ class WordSettings(): detection conversion settings for Microsoft Word documents. """ - def __init__(self, *, heading=None): + def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: """ Initialize a WordSettings object. @@ -12593,7 +13181,7 @@ def __init__(self, *, heading=None): self.heading = heading @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordSettings': """Initialize a WordSettings object from a json dictionary.""" args = {} valid_keys = ['heading'] @@ -12607,24 +13195,33 @@ def _from_dict(cls, _dict): _dict.get('heading')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordSettings 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, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict - def __str__(self): + 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 WordSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordSettings') -> 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): + def __ne__(self, other: 'WordSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12635,22 +13232,22 @@ class WordStyle(): :attr 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. + :attr List[str] names: (optional) Array of word style names to convert. """ - def __init__(self, *, level=None, names=None): + def __init__(self, *, level: int = None, names: List[str] = None) -> None: """ Initialize a WordStyle object. :param int level: (optional) HTML head level that content matching this style is tagged with. - :param list[str] names: (optional) Array of word style names to convert. + :param List[str] names: (optional) Array of word style names to convert. """ self.level = level self.names = names @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordStyle': """Initialize a WordStyle object from a json dictionary.""" args = {} valid_keys = ['level', 'names'] @@ -12665,7 +13262,12 @@ def _from_dict(cls, _dict): args['names'] = _dict.get('names') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordStyle 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, 'level') and self.level is not None: @@ -12674,17 +13276,21 @@ def _to_dict(self): _dict['names'] = self.names return _dict - def __str__(self): + 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 WordStyle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordStyle') -> 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): + def __ne__(self, other: 'WordStyle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12693,19 +13299,19 @@ class XPathPatterns(): """ Object containing an array of XPaths. - :attr list[str] xpaths: (optional) An array to XPaths. + :attr List[str] xpaths: (optional) An array to XPaths. """ - def __init__(self, *, xpaths=None): + def __init__(self, *, xpaths: List[str] = None) -> None: """ Initialize a XPathPatterns object. - :param list[str] xpaths: (optional) An array to XPaths. + :param List[str] xpaths: (optional) An array to XPaths. """ self.xpaths = xpaths @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'XPathPatterns': """Initialize a XPathPatterns object from a json dictionary.""" args = {} valid_keys = ['xpaths'] @@ -12718,23 +13324,812 @@ def _from_dict(cls, _dict): args['xpaths'] = _dict.get('xpaths') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a XPathPatterns 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, 'xpaths') and self.xpaths is not None: _dict['xpaths'] = self.xpaths return _dict - def __str__(self): + 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 XPathPatterns object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'XPathPatterns') -> 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: 'XPathPatterns') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Calculation(QueryAggregation): + """ + Calculation. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr float value: (optional) Value of the aggregation. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + value: float = None) -> None: + """ + Initialize a Calculation object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param float value: (optional) Value of the aggregation. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Calculation': + """Initialize a Calculation object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'value' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Calculation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Calculation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + 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 Calculation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Calculation') -> 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: 'Calculation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Filter(QueryAggregation): + """ + Filter. + + :attr str match: (optional) The match the aggregated results queried for. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + match: str = None) -> None: + """ + Initialize a Filter object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str match: (optional) The match the aggregated results queried for. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.match = match + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Filter': + """Initialize a Filter object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'match' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Filter: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'match' in _dict: + args['match'] = _dict.get('match') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Filter 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match + 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 Filter object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Filter') -> 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: 'Filter') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Histogram(QueryAggregation): + """ + Histogram. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr int interval: (optional) Interval of the aggregation. (For 'histogram' + type). + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + interval: int = None) -> None: + """ + Initialize a Histogram object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param int interval: (optional) Interval of the aggregation. (For + 'histogram' type). + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.interval = interval + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Histogram': + """Initialize a Histogram object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'interval' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Histogram: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Histogram 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + 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 Histogram object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Histogram') -> 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: 'Histogram') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Nested(QueryAggregation): + """ + Nested. + + :attr str path: (optional) The area of the results the aggregation was + restricted to. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + path: str = None) -> None: + """ + Initialize a Nested object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str path: (optional) The area of the results the aggregation was + restricted to. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.path = path + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Nested': + """Initialize a Nested object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'path' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Nested: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'path' in _dict: + args['path'] = _dict.get('path') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Nested 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + 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 Nested object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Nested') -> 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: 'Nested') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Term(QueryAggregation): + """ + Term. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr int count: (optional) The number of terms identified. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + count: int = None) -> None: + """ + Initialize a Term object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param int count: (optional) The number of terms identified. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Term': + """Initialize a Term object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'count' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Term: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Term 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + 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 Term object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Term') -> 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: 'Term') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Timeslice(QueryAggregation): + """ + Timeslice. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr str interval: (optional) Interval of the aggregation. Valid date interval + values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, + month/months, and year/years. + :attr bool anomaly: (optional) Used to indicate that anomaly detection should be + performed. Anomaly detection is used to locate unusual datapoints within a time + series. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + interval: str = None, + anomaly: bool = None) -> None: + """ + Initialize a Timeslice object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param str interval: (optional) Interval of the aggregation. Valid date + interval values are second/seconds minute/minutes, hour/hours, day/days, + week/weeks, month/months, and year/years. + :param bool anomaly: (optional) Used to indicate that anomaly detection + should be performed. Anomaly detection is used to locate unusual datapoints + within a time series. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.interval = interval + self.anomaly = anomaly + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Timeslice': + """Initialize a Timeslice object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'interval', 'anomaly' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Timeslice: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + if 'anomaly' in _dict: + args['anomaly'] = _dict.get('anomaly') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Timeslice 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'anomaly') and self.anomaly is not None: + _dict['anomaly'] = self.anomaly + 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 Timeslice object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Timeslice') -> 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: 'Timeslice') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TopHits(QueryAggregation): + """ + TopHits. + + :attr int size: (optional) Number of top hits returned by the aggregation. + :attr TopHitsResults hits: (optional) + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + size: int = None, + hits: 'TopHitsResults' = None) -> None: + """ + Initialize a TopHits object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param int size: (optional) Number of top hits returned by the aggregation. + :param TopHitsResults hits: (optional) + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.size = size + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TopHits': + """Initialize a TopHits object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'size', + 'hits' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TopHits: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'size' in _dict: + args['size'] = _dict.get('size') + if 'hits' in _dict: + args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TopHits 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'size') and self.size is not None: + _dict['size'] = self.size + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits._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 TopHits object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'TopHits') -> 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): + def __ne__(self, other: 'TopHits') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index ac731fb59..e1ed74b89 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,1423 +1,4777 @@ -# coding: utf-8 -import responses -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import io -import time -import jwt -from unittest import TestCase -import ibm_watson -from ibm_watson.discovery_v1 import TrainingDataSet, TrainingQuery, TrainingExample -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator - -from urllib.parse import urlparse, urljoin - -base_discovery_url = 'https://gateway.watsonplatform.net/discovery/api/v1/' - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/discovery/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -version = '2016-12-01' -environment_id = 'envid' -collection_id = 'collid' - - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": ["administrator", "manage_catalog"], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode( - access_token_layout, - 'secret', - algorithm='HS256', - headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - - -class TestDiscoveryV1(TestCase): - - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add(responses.POST, - url=iam_url, - body=json.dumps(iam_token_response), - status=200) - - @classmethod - @responses.activate - def test_environments(cls): - discovery_url = urljoin(base_discovery_url, 'environments') - discovery_response_body = """{ - "environments": [ - { - "environment_id": "string", - "name": "envname", - "description": "", - "created": "2016-11-20T01:03:17.645Z", - "updated": "2016-11-20T01:03:17.645Z", - "status": "status", - "index_capacity": { - "disk_usage": { - "used_bytes": 0, - "total_bytes": 0, - "used": "string", - "total": "string", - "percent_used": 0 - }, - "memory_usage": { - "used_bytes": 0, - "total_bytes": 0, - "used": "string", - "total": "string", - "percent_used": 0 - } - } - } - ] - }""" +import pytest +import responses +import tempfile +import ibm_watson.discovery_v1 +from ibm_watson.discovery_v1 import * - responses.add(responses.GET, - discovery_url, - body=discovery_response_body, - status=200, - content_type='application/json') +base_url = 'https://gateway.watsonplatform.net/discovery/api' - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.list_environments() +############################################################################## +# Start of Service: Environments +############################################################################## +# region - url_str = "{0}?version=2018-08-13".format(discovery_url) - assert responses.calls[0].request.url == url_str +#----------------------------------------------------------------------------- +# Test Class for create_environment +#----------------------------------------------------------------------------- +class TestCreateEnvironment(): - assert responses.calls[0].response.text == discovery_response_body + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.GET, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_create_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_environment(environment_id='envid') - url_str = "{0}?version=2018-08-13".format(discovery_url) - assert responses.calls[0].request.url == url_str + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_environments +#----------------------------------------------------------------------------- +class TestListEnvironments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_environments_response(self): + body = self.construct_full_body() + response = fake_response_ListEnvironmentsResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_create_environment(cls): + def test_list_environments_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListEnvironmentsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery_url = urljoin(base_discovery_url, 'environments') - responses.add(responses.POST, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_environments_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.create_environment(name="my name", - description="my description") + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_environments(**body) + return output + + def construct_full_body(self): + body = dict() + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_environment +#----------------------------------------------------------------------------- +class TestGetEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_update_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.PUT, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_get_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.update_environment('envid', name="hello", description="new") + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_environment +#----------------------------------------------------------------------------- +class TestUpdateEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.DELETE, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_update_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_environment +#----------------------------------------------------------------------------- +class TestDeleteEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_environment_response(self): + body = self.construct_full_body() + response = fake_response_DeleteEnvironmentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.delete_environment('envid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteEnvironmentResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_collections(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections') + def test_delete_environment_empty(self): + check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_fields +#----------------------------------------------------------------------------- +class TestListFields(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.list_collections('envid') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_empty(self): + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/fields'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_fields(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Configurations +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_configuration +#----------------------------------------------------------------------------- +class TestCreateConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_collection(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid') + def test_create_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery_fields = urljoin( - base_discovery_url, 'environments/envid/collections/collid/fields') - config_url = urljoin(base_discovery_url, - 'environments/envid/configurations') + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_configurations +#----------------------------------------------------------------------------- +class TestListConfigurations(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_response(self): + body = self.construct_full_body() + response = fake_response_ListConfigurationsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - config_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListConfigurationsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_fields, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_empty(self): + check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_configurations(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_configuration +#----------------------------------------------------------------------------- +class TestGetConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.DELETE, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - urljoin(base_discovery_url, - 'environments/envid/collections'), - body="{\"body\": \"create\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_configuration +#----------------------------------------------------------------------------- +class TestUpdateConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_collection(environment_id='envid', - name="name", - description="", - language="", - configuration_id='confid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_collection(environment_id='envid', - name="name", - language="es", - description="") + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_collection('envid', 'collid') + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_configuration +#----------------------------------------------------------------------------- +class TestDeleteConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_response(self): + body = self.construct_full_body() + response = fake_response_DeleteConfigurationResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - called_url = urlparse(responses.calls[2].request.url) - test_url = urlparse(discovery_url) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteConfigurationResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_empty(self): + check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.delete_collection(environment_id='envid', - collection_id='collid') - discovery.list_collection_fields(environment_id='envid', - collection_id='collid') - assert len(responses.calls) == 5 + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Configurations +############################################################################## + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_collection +#----------------------------------------------------------------------------- +class TestCreateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid/query') + def test_create_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_collections +#----------------------------------------------------------------------------- +class TestListCollections(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.federated_query('envid', - filter='colls.sha1::9181d244*', - collection_ids=['collid1', 'collid2']) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_empty(self): + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_collections(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_collection +#----------------------------------------------------------------------------- +class TestGetCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query_2(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid/query') + def test_get_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_collection +#----------------------------------------------------------------------------- +class TestUpdateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_collection +#----------------------------------------------------------------------------- +class TestDeleteCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_response(self): + body = self.construct_full_body() + response = fake_response_DeleteCollectionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteCollectionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.federated_query('envid', - collection_ids="'collid1', 'collid2'", - filter='colls.sha1::9181d244*', - bias='1', - logging_opt_out=True) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_empty(self): + check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_collection_fields +#----------------------------------------------------------------------------- +class TestListCollectionFields(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collection_fields_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collection_fields_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query_notices(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/notices') + def test_list_collection_fields_empty(self): + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.federated_query_notices('envid', - collection_ids=['collid1', 'collid2'], - filter='notices.sha1::9181d244*') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_collection_fields(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: QueryModifications +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_expansions +#----------------------------------------------------------------------------- +class TestListExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_expansions_response(self): + body = self.construct_full_body() + response = fake_response_Expansions_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_expansions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Expansions_json + send_request(self, body, response) + assert len(responses.calls) == 1 - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_expansions_empty(self): + check_empty_required_params(self, fake_response_Expansions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_expansions +#----------------------------------------------------------------------------- +class TestCreateExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_expansions_response(self): + body = self.construct_full_body() + response = fake_response_Expansions_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_query(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid/query') + def test_create_expansions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Expansions_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.query('envid', - 'collid', - filter='extracted_metadata.sha1::9181d244*', - count=1, - passages=True, - passages_fields=['x', 'y'], - logging_opt_out='True', - passages_count=2) - - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_query_2(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid/query') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_expansions_empty(self): + check_empty_required_params(self, fake_response_Expansions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.query('envid', - 'collid', - filter='extracted_metadata.sha1::9181d244*', - count=1, - passages=True, - passages_fields=['x', 'y'], - logging_opt_out='True', - passages_count=2, - bias='1', - collection_ids='1,2') - - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_query_notices(cls): - discovery_url = urljoin( - base_discovery_url, 'environments/envid/collections/collid/notices') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"expansions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"expansions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_expansions +#----------------------------------------------------------------------------- +class TestDeleteExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.query_notices('envid', 'collid', filter='notices.sha1::*') - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_tokenization_dictionary_status +#----------------------------------------------------------------------------- +class TestGetTokenizationDictionaryStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_tokenization_dictionary_status_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_configs(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/configurations') - discovery_config_id = urljoin( - base_discovery_url, 'environments/envid/configurations/confid') + def test_get_tokenization_dictionary_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - results = { - "configurations": [{ - "name": "Default Configuration", - "configuration_id": "confid" - }] - } + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_tokenization_dictionary_status_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body=json.dumps(results), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_tokenization_dictionary_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_tokenization_dictionary +#----------------------------------------------------------------------------- +class TestCreateTokenizationDictionary(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_config_id, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') - responses.add(responses.PUT, - discovery_config_id, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_tokenization_dictionary(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"tokenization_rules": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_tokenization_dictionary +#----------------------------------------------------------------------------- +class TestDeleteTokenizationDictionary(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_tokenization_dictionary_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_tokenization_dictionary_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_tokenization_dictionary_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - discovery_config_id, - body=json.dumps({'deleted': 'bogus -- ok'}), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.list_configurations(environment_id='envid') - - discovery.get_configuration(environment_id='envid', - configuration_id='confid') - - assert len(responses.calls) == 2 - - discovery.create_configuration(environment_id='envid', name='my name') - discovery.create_configuration(environment_id='envid', - name='my name', - source={ - 'type': 'salesforce', - 'credential_id': 'xxx' - }) - discovery.update_configuration(environment_id='envid', - configuration_id='confid', - name='my new name') - discovery.update_configuration(environment_id='envid', - configuration_id='confid', - name='my new name', - source={ - 'type': 'salesforce', - 'credential_id': 'xxx' - }) - discovery.delete_configuration(environment_id='envid', - configuration_id='confid') - - assert len(responses.calls) == 7 - - @classmethod - @responses.activate - def test_document(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/preview') - config_url = urljoin(base_discovery_url, - 'environments/envid/configurations') - responses.add(responses.POST, - discovery_url, - body="{\"configurations\": []}", - status=200, - content_type='application/json') - responses.add(responses.GET, - config_url, - body=json.dumps({ - "configurations": [{ - "name": "Default Configuration", - "configuration_id": "confid" - }] - }), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - add_doc_url = urljoin( - base_discovery_url, - 'environments/envid/collections/collid/documents') - - doc_id_path = 'environments/envid/collections/collid/documents/docid' - - update_doc_url = urljoin(base_discovery_url, doc_id_path) - del_doc_url = urljoin(base_discovery_url, doc_id_path) - responses.add(responses.POST, - add_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') - - doc_status = { - "document_id": - "45556e23-f2b1-449d-8f27-489b514000ff", - "configuration_id": - "2e079259-7dd2-40a9-998f-3e716f5a7b88", - "created": - "2016-06-16T10:56:54.957Z", - "updated": - "2017-05-16T13:56:54.957Z", - "status": - "available", - "status_description": - "Document is successfully ingested and indexed with no warnings", - "notices": [] - } + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_tokenization_dictionary(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_stopword_list_status +#----------------------------------------------------------------------------- +class TestGetStopwordListStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_stopword_list_status_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_stopword_list_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_stopword_list_status_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - del_doc_url, - body=json.dumps(doc_status), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_stopword_list_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_stopword_list +#----------------------------------------------------------------------------- +class TestCreateStopwordList(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_stopword_list_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_stopword_list_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_stopword_list_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - update_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_stopword_list(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['stopword_file'] = tempfile.NamedTemporaryFile() + body['stopword_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['stopword_file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_stopword_list +#----------------------------------------------------------------------------- +class TestDeleteStopwordList(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_stopword_list_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_stopword_list_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_stopword_list_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - del_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_stopword_list(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: QueryModifications +############################################################################## + +############################################################################## +# Start of Service: Documents +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for add_document +#----------------------------------------------------------------------------- +class TestAddDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - html_path = os.path.join(os.getcwd(), 'resources', 'simple.html') - with open(html_path) as fileinfo: - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=fileinfo) - assert conf_id is not None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.add_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_document_status +#----------------------------------------------------------------------------- +class TestGetDocumentStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) assert len(responses.calls) == 1 - discovery.get_document_status(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 2 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.update_document(environment_id='envid', - collection_id='collid', - document_id='docid') + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_document_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_document +#----------------------------------------------------------------------------- +class TestUpdateDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 3 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.update_document(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert len(responses.calls) == 4 + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_document +#----------------------------------------------------------------------------- +class TestDeleteDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_response(self): + body = self.construct_full_body() + response = fake_response_DeleteDocumentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.delete_document(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteDocumentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 5 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_empty(self): + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=io.StringIO(u'my string of file'), - filename='file.txt') + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Documents +############################################################################## + +############################################################################## +# Start of Service: Queries +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for query +#----------------------------------------------------------------------------- +class TestQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_response(self): + body = self.construct_full_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 6 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - conf_id = discovery.add_document( - environment_id='envid', - collection_id='collid', - file=io.StringIO(u'

my string of file

'), - filename='file.html', - file_content_type='application/html') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_empty(self): + check_empty_required_params(self, fake_response_QueryResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) + body['x_watson_logging_opt_out'] = True + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for query_notices +#----------------------------------------------------------------------------- +class TestQueryNotices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_response(self): + body = self.construct_full_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 7 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_empty(self): + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - conf_id = discovery.add_document( - environment_id='envid', - collection_id='collid', - file=io.StringIO(u'

my string of file

'), - filename='file.html', - file_content_type='application/html', - metadata=io.StringIO(u'{"stuff": "woot!"}')) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query_notices(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['filter'] = "string1" + body['query'] = "string1" + body['natural_language_query'] = "string1" + body['passages'] = True + body['aggregation'] = "string1" + body['count'] = 12345 + body['return_'] = [] + body['offset'] = 12345 + body['sort'] = [] + body['highlight'] = True + body['passages_fields'] = [] + body['passages_count'] = 12345 + body['passages_characters'] = 12345 + body['deduplicate_field'] = "string1" + body['similar'] = True + body['similar_document_ids'] = [] + body['similar_fields'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for federated_query +#----------------------------------------------------------------------------- +class TestFederatedQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_response(self): + body = self.construct_full_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 8 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_all_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_federated_query_empty(self): + check_empty_required_params(self, fake_response_QueryResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/query'.format(body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.federated_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body['x_watson_logging_opt_out'] = True + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for federated_query_notices +#----------------------------------------------------------------------------- +class TestFederatedQueryNotices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_response(self): + body = self.construct_full_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.delete_all_training_data( - environment_id=environment_id, - collection_id=collection_id).get_result() + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert response is None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_empty(self): + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/notices'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - @classmethod + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.federated_query_notices(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + body['filter'] = "string1" + body['query'] = "string1" + body['natural_language_query'] = "string1" + body['aggregation'] = "string1" + body['count'] = 12345 + body['return_'] = [] + body['offset'] = 12345 + body['sort'] = [] + body['highlight'] = True + body['deduplicate_field'] = "string1" + body['similar'] = True + body['similar_document_ids'] = [] + body['similar_fields'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_autocompletion +#----------------------------------------------------------------------------- +class TestGetAutocompletion(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_get_autocompletion_response(self): + body = self.construct_full_body() + response = fake_response_Completions_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_autocompletion_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Completions_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_autocompletion_empty(self): + check_empty_required_params(self, fake_response_Completions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "environment_id": - "string", - "collection_id": - "string", - "queries": [{ - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_autocompletion(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['prefix'] = "string1" + body['field'] = "string1" + body['count'] = 12345 + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['prefix'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Queries +############################################################################## + +############################################################################## +# Start of Service: TrainingData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_training_data +#----------------------------------------------------------------------------- +class TestListTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingDataSet_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingDataSet_json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.list_training_data( - environment_id=environment_id, - collection_id=collection_id).get_result() + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingDataSet_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert response == mock_response - # Verify that response can be converted to a TrainingDataSet - TrainingDataSet._from_dict(response) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_training_data +#----------------------------------------------------------------------------- +class TestAddTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_add_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_add_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - natural_language_query = "why is the sky blue" - filter = "text:meteorology" - examples = [{ - "document_id": "54f95ac0-3e4f-4756-bea6-7a67b2713c81", - "relevance": 1 - }, { - "document_id": "01bcca32-7300-4c9f-8d32-33ed7ea643da", - "cross_reference": "my_id_field:1463", - "relevance": 5 - }] - mock_response = { - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.add_training_data( - environment_id=environment_id, - collection_id=collection_id, - natural_language_query=natural_language_query, - filter=filter, - examples=examples).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingQuery - TrainingQuery._from_dict(response) - - @classmethod - @responses.activate - def test_delete_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' - query_id = 'queryid' - endpoint = training_endpoint.format(environment_id, collection_id, - query_id) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.add_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_all_training_data +#----------------------------------------------------------------------------- +class TestDeleteAllTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_all_training_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_all_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_all_training_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_all_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_data +#----------------------------------------------------------------------------- +class TestGetTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_training_data +#----------------------------------------------------------------------------- +class TestDeleteTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.delete_training_data( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert response is None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - @classmethod + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_training_examples +#----------------------------------------------------------------------------- +class TestListTrainingExamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' - query_id = 'queryid' - endpoint = training_endpoint.format(environment_id, collection_id, - query_id) + def test_list_training_examples_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExampleList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_examples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExampleList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_examples_empty(self): + check_empty_required_params(self, fake_response_TrainingExampleList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - response = discovery.get_training_data(environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingQuery - TrainingQuery._from_dict(response) - - @classmethod - @responses.activate - def test_create_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples' - query_id = 'queryid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_training_examples(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_training_example +#----------------------------------------------------------------------------- +class TestCreateTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - document_id = "string" - relevance = 0 - cross_reference = "string" - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(mock_response), - status=201, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.create_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - document_id=document_id, - relevance=relevance, - cross_reference=cross_reference).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_delete_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) - url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - response = discovery.delete_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id).get_result() - - assert response is None - - @classmethod - @responses.activate - def test_get_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_training_example +#----------------------------------------------------------------------------- +class TestDeleteTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_example_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_example_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } - responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.get_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_update_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_training_example +#----------------------------------------------------------------------------- +class TestUpdateTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) url = '{0}{1}'.format(base_url, endpoint) - relevance = 0 - cross_reference = "string" - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } + return url + + def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.update_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id, - relevance=relevance, - cross_reference=cross_reference).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_expansions(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/expansions' + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + body.update({"cross_reference": "string1", "relevance": 12345, }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + body.update({"cross_reference": "string1", "relevance": 12345, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_example +#----------------------------------------------------------------------------- +class TestGetTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body='{"expansions": "results"}', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: TrainingData +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body='{"description": "success" }', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + +############################################################################## +# Start of Service: EventsAndFeedback +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_event +#----------------------------------------------------------------------------- +class TestCreateEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_event_response(self): + body = self.construct_full_body() + response = fake_response_CreateEventResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CreateEventResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_event_empty(self): + check_empty_required_params(self, fake_response_CreateEventResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/events' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body='{"expansions": "success" }', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_event(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + return body + + def construct_required_body(self): + body = dict() + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for query_log +#----------------------------------------------------------------------------- +class TestQueryLog(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_response(self): + body = self.construct_full_body() + response = fake_response_LogQueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogQueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.list_expansions('envid', 'colid') - assert responses.calls[0].response.json() == {"expansions": "results"} + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.create_expansions('envid', 'colid', [{ - "input_terms": "dumb", - "expanded_terms": "dumb2" - }]) - assert responses.calls[1].response.json() == {"expansions": "success"} + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/logs' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.delete_expansions('envid', 'colid') - assert responses.calls[2].response.json() == {"description": "success"} + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query_log(**body) + return output + + def construct_full_body(self): + body = dict() + body['filter'] = "string1" + body['query'] = "string1" + body['count'] = 12345 + body['offset'] = 12345 + body['sort'] = [] + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query +#----------------------------------------------------------------------------- +class TestGetMetricsQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 3 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_user_data(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/user_data' - responses.add(responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_credentials(cls): - discovery_credentials_url = urljoin(base_discovery_url, - 'environments/envid/credentials') - - results = { - 'credential_id': 'e68305ce-29f3-48ea-b829-06653ca0fdef', - 'source_type': 'salesforce', - 'credential_details': { - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username': 'user@email.com' - } - } - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + def test_get_metrics_query_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps(results), - status=200, - content_type='application/json') - responses.add( - responses.GET, - "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps([results]), - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps(results), - status=200, - content_type='application/json') - results['source_type'] = 'ibm' - responses.add(responses.PUT, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps(results), - status=200, - content_type='application/json') - responses.add(responses.DELETE, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps({'deleted': 'bogus -- ok'}), - status=200, - content_type='application/json') - - discovery.create_credentials('envid', - source_type='salesforce', - credential_details={ - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username': 'user@email.com' - }) - - discovery.get_credentials('envid', 'credential_id') - - discovery.update_credentials( - environment_id='envid', - credential_id='credential_id', - source_type='salesforce', - credential_details=results['credential_details']) - discovery.list_credentials('envid') - discovery.delete_credentials(environment_id='envid', - credential_id='credential_id') - assert len(responses.calls) == 10 - - @classmethod - @responses.activate - def test_events_and_feedback(cls): - discovery_event_url = urljoin(base_discovery_url, 'events') - discovery_metrics_event_rate_url = urljoin(base_discovery_url, - 'metrics/event_rate') - discovery_metrics_query_url = urljoin(base_discovery_url, - 'metrics/number_of_queries') - discovery_metrics_query_event_url = urljoin( - base_discovery_url, 'metrics/number_of_queries_with_event') - discovery_metrics_query_no_results_url = urljoin( - base_discovery_url, - 'metrics/number_of_queries_with_no_search_results') - discovery_metrics_query_token_event_url = urljoin( - base_discovery_url, 'metrics/top_query_tokens_with_event_rate') - discovery_query_log_url = urljoin(base_discovery_url, 'logs') - - event_data = { - "environment_id": "xxx", - "session_token": "yyy", - "client_timestamp": "2018-08-14T14:39:59.268Z", - "display_rank": 0, - "collection_id": "abc", - "document_id": "xyz", - "query_id": "cde" - } - - create_event_response = {"type": "click", "data": event_data} - - metric_response = { - "aggregations": [{ - "interval": - "1d", - "event_type": - "click", - "results": [{ - "key_as_string": "2018-08-14T14:39:59.309Z", - "key": 1533513600000, - "matching_results": 2, - "event_rate": 0.0 - }] - }] - } - - metric_token_response = { - "aggregations": [{ - "event_type": - "click", - "results": [{ - "key": "content", - "matching_results": 5, - "event_rate": 0.6 - }, { - "key": "first", - "matching_results": 5, - "event_rate": 0.6 - }, { - "key": "of", - "matching_results": 5, - "event_rate": 0.6 - }] - }] - } - - log_query_response = { - "matching_results": - 20, - "results": [{ - "customer_id": "", - "environment_id": "xxx", - "natural_language_query": "The content of the first chapter", - "query_id": "1ICUdh3Pab", - "document_results": { - "count": - 1, - "results": [{ - "collection_id": "b67a82f3-6507-4c25-9757-3485ff4f2a32", - "score": 0.025773458, - "position": 10, - "document_id": "af0be20e-e130-4712-9a2e-37d9c8b9c52f" - }] - }, - "event_type": "query", - "session_token": "1_nbEfQtKVcg9qx3t41ICUdh3Pab", - "created_timestamp": "2018-08-14T18:20:30.460Z" - }] - } + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_event +#----------------------------------------------------------------------------- +class TestGetMetricsQueryEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - "{0}?version=2018-08-13".format(discovery_event_url), - body=json.dumps(create_event_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_event_rate_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_event_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_no_results_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries_with_event' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13&count=2".format( - discovery_metrics_query_token_event_url), - body=json.dumps(metric_token_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_event(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_no_results +#----------------------------------------------------------------------------- +class TestGetMetricsQueryNoResults(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_no_results_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_no_results_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_no_results_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries_with_no_search_results' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13".format(discovery_query_log_url), - body=json.dumps(log_query_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_no_results(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_event_rate +#----------------------------------------------------------------------------- +class TestGetMetricsEventRate(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_event('click', event_data) - assert responses.calls[1].response.json()["data"] == event_data + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.get_metrics_event_rate(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[3].response.json() == metric_response + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/event_rate' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_metrics_query(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[5].response.json() == metric_response + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_event_rate(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_token_event +#----------------------------------------------------------------------------- +class TestGetMetricsQueryTokenEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_response(self): + body = self.construct_full_body() + response = fake_response_MetricTokenResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.get_metrics_query_event(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[7].response.json() == metric_response + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricTokenResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.get_metrics_query_no_results( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[9].response.json() == metric_response + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.get_metrics_query_token_event(count=2) - assert responses.calls[11].response.json() == metric_token_response + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/top_query_tokens_with_event_rate' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.query_log() - assert responses.calls[13].response.json() == log_query_response + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_token_event(**body) + return output + + def construct_full_body(self): + body = dict() + body['count'] = 12345 + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: EventsAndFeedback +############################################################################## + +############################################################################## +# Start of Service: Credentials +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_credentials +#----------------------------------------------------------------------------- +class TestListCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_credentials_response(self): + body = self.construct_full_body() + response = fake_response_CredentialsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 14 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CredentialsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_tokenization_dictionary(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/tokenization_dictionary?version=2018-08-13' - responses.add(responses.POST, - url, - body='{"status": "pending"}', - status=200, - content_type='application_json') - responses.add(responses.DELETE, - url, - body='{"status": "pending"}', - status=200) - responses.add( - responses.GET, - url, - body='{"status": "pending", "type":"tokenization_dictionary"}', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - tokenization_rules = [{ - 'text': 'token', - 'tokens': ['token 1', 'token 2'], - 'readings': ['reading 1', 'reading 2'], - 'part_of_speech': 'noun', - }] - - discovery.create_tokenization_dictionary( - 'envid', 'colid', tokenization_rules=tokenization_rules) - assert responses.calls[0].response.json() == {"status": "pending"} - - discovery.get_tokenization_dictionary_status('envid', 'colid') - assert responses.calls[1].response.json() == { - "status": "pending", - "type": "tokenization_dictionary" - } - - discovery.delete_tokenization_dictionary('envid', 'colid') - assert responses.calls[2].response.status_code == 200 - - assert len(responses.calls) == 3 - - @classmethod - @responses.activate - def test_stopword_operations(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/stopwords?version=2018-08-13' + def test_list_credentials_empty(self): + check_empty_required_params(self, fake_response_CredentialsList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_credentials +#----------------------------------------------------------------------------- +class TestCreateCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body='{"status": "pending", "type": "stopwords"}', - status=200, - content_type='application_json') - responses.add(responses.DELETE, url, status=200) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_credentials +#----------------------------------------------------------------------------- +class TestGetCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body='{"status": "ready", "type": "stopwords"}', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - stopwords_file_path = os.path.join(os.getcwd(), 'resources', - 'stopwords.txt') - with open(stopwords_file_path) as file: - discovery.create_stopword_list('envid', 'colid', file) - assert responses.calls[0].response.json() == { - "status": "pending", - "type": "stopwords" - } - - discovery.get_stopword_list_status('envid', 'colid') - assert responses.calls[1].response.json() == { - "status": "ready", - "type": "stopwords" - } - - discovery.delete_stopword_list('envid', 'colid') - assert responses.calls[2].response.status_code == 200 - - assert len(responses.calls) == 3 - - @classmethod - @responses.activate - def test_gateway_configuration(cls): - discovery_gateway_url = urljoin(base_discovery_url, - 'environments/envid/gateways') - - gateway_details = { - "status": "idle", - "token_id": "9GnaCreixek_prod_ng", - "token": "4FByv9Mmd79x6c", - "name": "test-gateway-configuration-python", - "gateway_id": "gateway_id" - } + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_credentials +#----------------------------------------------------------------------------- +class TestUpdateCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_credentials +#----------------------------------------------------------------------------- +class TestDeleteCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_credentials_response(self): + body = self.construct_full_body() + response = fake_response_DeleteCredentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteCredentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_credentials_empty(self): + check_empty_required_params(self, fake_response_DeleteCredentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Credentials +############################################################################## + +############################################################################## +# Start of Service: GatewayConfiguration +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_gateways +#----------------------------------------------------------------------------- +class TestListGateways(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_gateways_response(self): + body = self.construct_full_body() + response = fake_response_GatewayList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_gateways_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GatewayList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_gateways_empty(self): + check_empty_required_params(self, fake_response_GatewayList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}/{1}?version=2018-08-13".format( - discovery_gateway_url, 'gateway_id'), - body=json.dumps(gateway_details), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_gateways(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_gateway +#----------------------------------------------------------------------------- +class TestCreateGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_gateway_response(self): + body = self.construct_full_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_gateway_empty(self): + check_empty_required_params(self, fake_response_Gateway_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - "{0}?version=2018-08-13".format(discovery_gateway_url), - body=json.dumps(gateway_details), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_gateway +#----------------------------------------------------------------------------- +class TestGetGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_gateway_response(self): + body = self.construct_full_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_gateway_empty(self): + check_empty_required_params(self, fake_response_Gateway_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13".format(discovery_gateway_url), - body=json.dumps({'gateways': [gateway_details]}), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_gateway +#----------------------------------------------------------------------------- +class TestDeleteGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_gateway_response(self): + body = self.construct_full_body() + response = fake_response_GatewayDelete_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GatewayDelete_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_gateway_empty(self): + check_empty_required_params(self, fake_response_GatewayDelete_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - "{0}/{1}?version=2018-08-13".format( - discovery_gateway_url, 'gateway_id'), - body=json.dumps({ - 'gateway_id': 'gateway_id', - 'status': 'deleted' - }), - status=200, - content_type='application/json') - - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - discovery.create_gateway('envid', name='gateway_id') - discovery.list_gateways('envid') - discovery.get_gateway('envid', 'gateway_id') - discovery.delete_gateway(environment_id='envid', - gateway_id='gateway_id') - assert len(responses.calls) == 8 - - @responses.activate - def test_get_autocompletion(self): - endpoint = 'environments/{0}/collections/{1}/autocompletion?version=2018-08-13&field=field&prefix=prefix&count=count'.format( - 'environment_id', 'collection_id').format('collection_id') - url = '{0}{1}'.format(base_discovery_url, endpoint) - print('hello') - print(url) - response = {"completions": ["completions", "completions"]} - responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - detailed_response = discovery.get_autocompletion( - environment_id='environment_id', - collection_id='collection_id', - field='field', - prefix='prefix', - count='count') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: GatewayConfiguration +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_ListEnvironmentsResponse_json = """{"environments": []}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_DeleteEnvironmentResponse_json = """{"environment_id": "fake_environment_id", "status": "fake_status"}""" +fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_ListConfigurationsResponse_json = """{"configurations": []}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_DeleteConfigurationResponse_json = """{"configuration_id": "fake_configuration_id", "status": "fake_status", "notices": []}""" +fake_response_Collection_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_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": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +fake_response_ListCollectionsResponse_json = """{"collections": []}""" +fake_response_Collection_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_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": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +fake_response_Collection_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_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": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +fake_response_DeleteCollectionResponse_json = """{"collection_id": "fake_collection_id", "status": "fake_status"}""" +fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" +fake_response_Expansions_json = """{"expansions": []}""" +fake_response_Expansions_json = """{"expansions": []}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "configuration_id": "fake_configuration_id", "status": "fake_status", "status_description": "fake_status_description", "filename": "fake_filename", "file_type": "fake_file_type", "sha1": "fake_sha1", "notices": []}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" +fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" +fake_response_Completions_json = """{"completions": []}""" +fake_response_TrainingDataSet_json = """{"environment_id": "fake_environment_id", "collection_id": "fake_collection_id", "queries": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingExampleList_json = """{"examples": []}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_CreateEventResponse_json = """{"type": "fake_type", "data": {"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}}""" +fake_response_LogQueryResponse_json = """{"matching_results": 16, "results": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricTokenResponse_json = """{"aggregations": []}""" +fake_response_CredentialsList_json = """{"credentials": []}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_DeleteCredentials_json = """{"credential_id": "fake_credential_id", "status": "fake_status"}""" +fake_response_GatewayList_json = """{"gateways": []}""" +fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" +fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" +fake_response_GatewayDelete_json = """{"gateway_id": "fake_gateway_id", "status": "fake_status"}""" From 2f142fb21953c3afa10c4f0ed6f8e4922cfa8672 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 15:02:07 -0500 Subject: [PATCH 07/28] refactor(discoveryv2): regenerate discovery v2 with tests --- ibm_watson/discovery_v2.py | 3168 +++++++++++++++++++------------- test/unit/test_discovery_v2.py | 341 ++-- 2 files changed, 2091 insertions(+), 1418 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index ef9dc5b8f..0af5456bd 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,21 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO +import sys ############################################################################## # Service @@ -38,13 +46,15 @@ class DiscoveryV2(BaseService): """The Discovery V2 service.""" - default_service_url = None + DEFAULT_SERVICE_URL = None + DEFAULT_SERVICE_NAME = 'discovery' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Discovery service. @@ -63,30 +73,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('discovery') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('discovery') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Collections ######################### - def list_collections(self, project_id, **kwargs): + def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': """ List collections. @@ -105,7 +105,9 @@ def list_collections(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = {'version': self.version} @@ -115,8 +117,8 @@ def list_collections(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -125,23 +127,23 @@ def list_collections(self, project_id, **kwargs): ######################### def query(self, - project_id, + project_id: str, *, - collection_ids=None, - filter=None, - query=None, - natural_language_query=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - spelling_suggestions=None, - table_results=None, - suggested_refinements=None, - passages=None, - **kwargs): + 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, + **kwargs) -> 'DetailedResponse': """ Query a project. @@ -150,7 +152,7 @@ def query(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param list[str] collection_ids: (optional) A comma-separated list of + :param List[str] collection_ids: (optional) A comma-separated list of collection IDs to be queried against. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for @@ -167,7 +169,7 @@ def query(self, applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. - :param list[str] return_: (optional) A list of the fields in the document + :param List[str] return_: (optional) A list of the fields in the document hierarchy to return. If this parameter not specified, then all top-level fields are returned. :param int offset: (optional) The number of query results to skip at the @@ -209,7 +211,9 @@ def query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query') headers.update(sdk_headers) params = {'version': self.version} @@ -237,19 +241,19 @@ def query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_autocompletion(self, - project_id, - prefix, + project_id: str, + prefix: str, *, - collection_ids=None, - field=None, - count=None, - **kwargs): + collection_ids: List[str] = None, + field: str = None, + count: int = None, + **kwargs) -> 'DetailedResponse': """ Get Autocomplete Suggestions. @@ -260,7 +264,7 @@ def get_autocompletion(self, :param str prefix: The prefix to use for autocompletion. For example, the prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. Possible completions are. - :param list[str] collection_ids: (optional) Comma separated list of the + :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. :param str field: (optional) The field in the result documents that @@ -280,7 +284,9 @@ def get_autocompletion(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = { @@ -296,20 +302,20 @@ def get_autocompletion(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def query_notices(self, - project_id, + project_id: str, *, - filter=None, - query=None, - natural_language_query=None, - count=None, - offset=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> 'DetailedResponse': """ Query system notices. @@ -345,7 +351,9 @@ def query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = { @@ -362,12 +370,16 @@ def query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_fields(self, project_id, *, collection_ids=None, **kwargs): + def list_fields(self, + project_id: str, + *, + collection_ids: List[str] = None, + **kwargs) -> 'DetailedResponse': """ List fields. @@ -376,7 +388,7 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param list[str] collection_ids: (optional) Comma separated list of the + :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. :param dict headers: A `dict` containing the request headers @@ -390,7 +402,9 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = { @@ -403,8 +417,8 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -412,7 +426,8 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): # Component settings ######################### - def get_component_settings(self, project_id, **kwargs): + def get_component_settings(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ Configuration settings for components. @@ -431,8 +446,9 @@ def get_component_settings(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - '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 = {'version': self.version} @@ -442,8 +458,8 @@ def get_component_settings(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -452,15 +468,15 @@ def get_component_settings(self, project_id, **kwargs): ######################### def add_document(self, - project_id, - collection_id, + project_id: str, + collection_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - x_watson_discovery_force=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a document. @@ -485,15 +501,15 @@ def add_document(self, **Note:** Documents can be added with a specific **document_id** by using the **_/v2/projects/{project_id}/collections/{collection_id}/documents** method. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -518,7 +534,9 @@ def add_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = {'version': self.version} @@ -532,6 +550,7 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v2/projects/{0}/collections/{1}/documents'.format( @@ -540,22 +559,22 @@ def add_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response def update_document(self, - project_id, - collection_id, - document_id, + project_id: str, + collection_id: str, + document_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - x_watson_discovery_force=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Update a document. @@ -566,16 +585,16 @@ def update_document(self, **Note:** When uploading a new document with this method it automatically replaces any document stored with the same **document_id** if it exists. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -602,7 +621,9 @@ def update_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = {'version': self.version} @@ -616,6 +637,7 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( @@ -624,18 +646,18 @@ def update_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response def delete_document(self, - project_id, - collection_id, - document_id, + project_id: str, + collection_id: str, + document_id: str, *, - x_watson_discovery_force=None, - **kwargs): + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Delete a document. @@ -643,7 +665,7 @@ def delete_document(self, success response is returned (HTTP status code `200`) with the status set to 'deleted'. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found @@ -668,7 +690,9 @@ def delete_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = {'version': self.version} @@ -678,8 +702,8 @@ def delete_document(self, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -687,7 +711,8 @@ def delete_document(self, # Training data ######################### - def list_training_queries(self, project_id, **kwargs): + def list_training_queries(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ List training queries. @@ -706,8 +731,9 @@ def list_training_queries(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - '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 = {'version': self.version} @@ -717,12 +743,13 @@ def list_training_queries(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_training_queries(self, project_id, **kwargs): + def delete_training_queries(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ Delete training queries. @@ -741,8 +768,9 @@ def delete_training_queries(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - '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 = {'version': self.version} @@ -752,18 +780,18 @@ def delete_training_queries(self, project_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def create_training_query(self, - project_id, - natural_language_query, - examples, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], *, - filter=None, - **kwargs): + filter: str = None, + **kwargs) -> 'DetailedResponse': """ Create training query. @@ -774,7 +802,7 @@ def create_training_query(self, from the deploy page of the Discovery administrative tooling. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :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. :param dict headers: A `dict` containing the request headers @@ -784,13 +812,18 @@ def create_training_query(self, if project_id is None: raise ValueError('project_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - '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 = {'version': self.version} @@ -807,12 +840,13 @@ def create_training_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_query(self, project_id, query_id, **kwargs): + def get_training_query(self, project_id: str, query_id: str, + **kwargs) -> 'DetailedResponse': """ Get a training data query. @@ -835,7 +869,9 @@ def get_training_query(self, project_id, query_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', '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 = {'version': self.version} @@ -845,19 +881,19 @@ def get_training_query(self, project_id, query_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_training_query(self, - project_id, - query_id, - natural_language_query, - examples, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], *, - filter=None, - **kwargs): + filter: str = None, + **kwargs) -> 'DetailedResponse': """ Update a training query. @@ -868,7 +904,7 @@ def update_training_query(self, :param str query_id: The ID of the query used for training. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :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. :param dict headers: A `dict` containing the request headers @@ -889,8 +925,9 @@ def update_training_query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - '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 = {'version': self.version} @@ -907,8 +944,8 @@ def update_training_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -954,7 +991,7 @@ class Collection(): :attr str name: (optional) The name of the collection. """ - def __init__(self, *, collection_id=None, name=None): + def __init__(self, *, collection_id: str = None, name: str = None) -> None: """ Initialize a Collection object. @@ -966,7 +1003,7 @@ def __init__(self, *, collection_id=None, name=None): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'name'] @@ -981,7 +1018,12 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -990,17 +1032,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1009,21 +1055,21 @@ class Completions(): """ An object containing an array of autocompletion suggestions. - :attr list[str] completions: (optional) Array of autcomplete suggestion based on + :attr List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions=None): + def __init__(self, *, completions: List[str] = None) -> None: """ Initialize a Completions object. - :param list[str] completions: (optional) Array of autcomplete suggestion + :param List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ self.completions = completions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} valid_keys = ['completions'] @@ -1036,24 +1082,33 @@ def _from_dict(cls, _dict): args['completions'] = _dict.get('completions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: _dict['completions'] = self.completions return _dict - def __str__(self): + 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 Completions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Completions') -> 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): + def __ne__(self, other: 'Completions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1073,10 +1128,10 @@ class ComponentSettingsAggregation(): def __init__(self, *, - name=None, - label=None, - multiple_selections_allowed=None, - visualization_type=None): + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: """ Initialize a ComponentSettingsAggregation object. @@ -1094,7 +1149,7 @@ def __init__(self, self.visualization_type = visualization_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': """Initialize a ComponentSettingsAggregation object from a json dictionary.""" args = {} valid_keys = [ @@ -1116,7 +1171,12 @@ def _from_dict(cls, _dict): args['visualization_type'] = _dict.get('visualization_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation 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: @@ -1133,17 +1193,21 @@ def _to_dict(self): _dict['visualization_type'] = self.visualization_type return _dict - def __str__(self): + 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 ComponentSettingsAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsAggregation') -> 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): + def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1165,7 +1229,10 @@ class ComponentSettingsFieldsShown(): :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. """ - def __init__(self, *, body=None, title=None): + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: """ Initialize a ComponentSettingsFieldsShown object. @@ -1176,7 +1243,7 @@ def __init__(self, *, body=None, title=None): self.title = title @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} valid_keys = ['body', 'title'] @@ -1193,7 +1260,12 @@ def _from_dict(cls, _dict): _dict.get('title')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown 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, 'body') and self.body is not None: @@ -1202,17 +1274,21 @@ def _to_dict(self): _dict['title'] = self.title._to_dict() return _dict - def __str__(self): + 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 ComponentSettingsFieldsShown object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1225,7 +1301,7 @@ class ComponentSettingsFieldsShownBody(): :attr str field: (optional) Use a specific field as the title. """ - def __init__(self, *, use_passage=None, field=None): + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: """ Initialize a ComponentSettingsFieldsShownBody object. @@ -1236,7 +1312,7 @@ def __init__(self, *, use_passage=None, field=None): self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} valid_keys = ['use_passage', 'field'] @@ -1251,7 +1327,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody 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, 'use_passage') and self.use_passage is not None: @@ -1260,17 +1341,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 ComponentSettingsFieldsShownBody object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1282,7 +1367,7 @@ class ComponentSettingsFieldsShownTitle(): :attr str field: (optional) Use a specific field as the title. """ - def __init__(self, *, field=None): + def __init__(self, *, field: str = None) -> None: """ Initialize a ComponentSettingsFieldsShownTitle object. @@ -1291,7 +1376,7 @@ def __init__(self, *, field=None): self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" args = {} valid_keys = ['field'] @@ -1304,24 +1389,33 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle 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, 'field') and self.field is not None: _dict['field'] = self.field return _dict - def __str__(self): + 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 ComponentSettingsFieldsShownTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1336,17 +1430,18 @@ class ComponentSettingsResponse(): :attr 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 + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ def __init__(self, *, - fields_shown=None, - autocomplete=None, - structured_search=None, - results_per_page=None, - aggregations=None): + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None + ) -> None: """ Initialize a ComponentSettingsResponse object. @@ -1357,7 +1452,7 @@ def __init__(self, :param bool structured_search: (optional) Whether or not structured search is enabled. :param int results_per_page: (optional) Number or results shown per page. - :param list[ComponentSettingsAggregation] aggregations: (optional) a list + :param List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ self.fields_shown = fields_shown @@ -1367,7 +1462,7 @@ def __init__(self, self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -1395,7 +1490,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsResponse 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, 'fields_shown') and self.fields_shown is not None: @@ -1412,17 +1512,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 ComponentSettingsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsResponse') -> 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): + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1436,7 +1540,7 @@ class DeleteDocumentResponse(): status deleted. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DeleteDocumentResponse object. @@ -1448,7 +1552,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -1463,7 +1567,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: @@ -1472,17 +1581,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteDocumentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteDocumentResponse') -> 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): + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1505,7 +1618,7 @@ class DocumentAccepted(): others. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DocumentAccepted object. @@ -1520,7 +1633,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -1535,7 +1648,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: @@ -1544,17 +1662,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DocumentAccepted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAccepted') -> 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): + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1579,7 +1701,11 @@ class DocumentAttribute(): `begin` and `end`. """ - def __init__(self, *, type=None, text=None, location=None): + def __init__(self, + *, + type: str = None, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ Initialize a DocumentAttribute object. @@ -1594,7 +1720,7 @@ def __init__(self, *, type=None, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': """Initialize a DocumentAttribute object from a json dictionary.""" args = {} valid_keys = ['type', 'text', 'location'] @@ -1612,7 +1738,12 @@ def _from_dict(cls, _dict): _dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAttribute 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, 'type') and self.type is not None: @@ -1623,17 +1754,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 DocumentAttribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAttribute') -> 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): + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1648,7 +1783,11 @@ class Field(): the field was found. """ - def __init__(self, *, field=None, type=None, collection_id=None): + def __init__(self, + *, + field: str = None, + type: str = None, + collection_id: str = None) -> None: """ Initialize a Field object. @@ -1662,7 +1801,7 @@ def __init__(self, *, field=None, type=None, collection_id=None): self.collection_id = collection_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} valid_keys = ['field', 'type', 'collection_id'] @@ -1679,7 +1818,12 @@ def _from_dict(cls, _dict): args['collection_id'] = _dict.get('collection_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Field 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, 'field') and self.field is not None: @@ -1690,17 +1834,21 @@ def _to_dict(self): _dict['collection_id'] = self.collection_id return _dict - def __str__(self): + 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 Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Field') -> 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): + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1725,21 +1873,21 @@ class ListCollectionsResponse(): """ Response object containing an array of collection details. - :attr list[Collection] collections: (optional) An array containing information + :attr List[Collection] collections: (optional) An array containing information about each collection in the project. """ - def __init__(self, *, collections=None): + def __init__(self, *, collections: List['Collection'] = None) -> None: """ Initialize a ListCollectionsResponse object. - :param list[Collection] collections: (optional) An array containing + :param List[Collection] collections: (optional) An array containing information about each collection in the project. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1754,24 +1902,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionsResponse') -> 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): + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1786,21 +1943,21 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr list[Field] fields: (optional) An array containing information about each + :attr List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields=None): + def __init__(self, *, fields: List['Field'] = None) -> None: """ Initialize a ListFieldsResponse object. - :param list[Field] fields: (optional) An array containing information about + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ self.fields = fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} valid_keys = ['fields'] @@ -1815,24 +1972,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListFieldsResponse 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, 'fields') and self.fields is not None: _dict['fields'] = [x._to_dict() for x in self.fields] return _dict - def __str__(self): + 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 ListFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListFieldsResponse') -> 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): + def __ne__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1869,14 +2035,14 @@ class Notice(): def __init__(self, *, - notice_id=None, - created=None, - document_id=None, - collection_id=None, - query_id=None, - severity=None, - step=None, - description=None): + 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: """ Initialize a Notice object. @@ -1915,7 +2081,7 @@ def __init__(self, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} valid_keys = [ @@ -1945,7 +2111,12 @@ def _from_dict(cls, _dict): args['description'] = _dict.get('description') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice 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, 'notice_id') and self.notice_id is not None: @@ -1966,17 +2137,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Notice') -> 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): + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1997,7 +2172,7 @@ class QueryAggregation(): top_hits. """ - def __init__(self, type): + def __init__(self, type: str) -> None: """ Initialize a QueryAggregation object. @@ -2008,8 +2183,11 @@ def __init__(self, type): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryAggregation': """Initialize a QueryAggregation object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) args = {} valid_keys = ['type'] bad_keys = set(_dict.keys()) - set(valid_keys) @@ -2025,352 +2203,170 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregation 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, 'type') and self.type is not None: _dict['type'] = self.type return _dict - def __str__(self): + 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 QueryAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryAggregation') -> 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): + def __ne__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['term'] = 'QueryTermAggregation' + mapping['histogram'] = 'QueryHistogramAggregation' + mapping['timeslice'] = 'QueryTimesliceAggregation' + mapping['nested'] = 'QueryNestedAggregation' + mapping['filter'] = 'QueryFilterAggregation' + mapping['min'] = 'QueryCalculationAggregation' + mapping['max'] = 'QueryCalculationAggregation' + mapping['sum'] = 'QueryCalculationAggregation' + mapping['average'] = 'QueryCalculationAggregation' + mapping['unique_count'] = 'QueryCalculationAggregation' + mapping['top_hits'] = 'QueryTopHitsAggregation' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in QueryAggregation JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + -class QueryCalculationAggregation(): +class QueryHistogramAggregationResult(): """ - Returns a scalar calculation across all documents for the field specified. Possible - calculations include min, max, sum, average, and unique_count. + Histogram numeric interval result. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :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 + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - def __init__(self, type, field, *, value=None): + def __init__(self, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a QueryCalculationAggregation object. + Initialize a QueryHistogramAggregationResult object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. + :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. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - self.field = field - self.value = value + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': + """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['field', 'value'] + valid_keys = ['key', 'matching_results', 'aggregations'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'key' in _dict: + args['key'] = _dict.get('key') else: raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' + 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregationResult 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, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this QueryCalculationAggregation object.""" + 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 QueryHistogramAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryHistogramAggregationResult') -> 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): + def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryFilterAggregation(): +class QueryLargePassages(): """ - A modifier that will narrow down the document set of the sub aggregations it precedes. - - :attr str match: The filter written in Discovery Query Language syntax applied - to the documents before sub aggregations are run. - :attr int matching_results: Number of documents matching the filter. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, type, match, matching_results, *, aggregations=None): - """ - Initialize a QueryFilterAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str match: The filter written in Discovery Query Language syntax - applied to the documents before sub aggregations are run. - :param int matching_results: Number of documents matching the filter. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.match = match - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" - args = {} - valid_keys = ['match', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' - + ', '.join(bad_keys)) - if 'match' in _dict: - args['match'] = _dict.get('match') - else: - raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryFilterAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryHistogramAggregation(): - """ - 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 the results are split into. - :attr list[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. - """ - - def __init__(self, type, field, interval, *, results=None): - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections the results are split into. - :param list[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - self.field = field - self.interval = interval - self.results = results - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if 'results' in _dict: - args['results'] = [ - QueryHistogramAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict - - def __str__(self): - """Return a `str` version of this QueryHistogramAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -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 - upper bound. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, key, matching_results, *, aggregations=None): - """ - Initialize a QueryHistogramAggregationResult object. - - :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. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' - + ', '.join(bad_keys)) - if 'key' in _dict: - args['key'] = _dict.get('key') - else: - raise ValueError( - 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryHistogramAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryLargePassages(): - """ - Configuration for passage retrieval. + Configuration for passage retrieval. :attr bool enabled: (optional) A passages query that returns the most relevant passages from the results. :attr bool per_document: (optional) When `true`, passages will be returned - whithin their respective result. + within their respective result. :attr int max_per_document: (optional) Maximum number of passages to return per result. - :attr list[str] fields: (optional) A list of fields that passages are drawn + :attr List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :attr int count: (optional) The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. @@ -2381,22 +2377,22 @@ class QueryLargePassages(): def __init__(self, *, - enabled=None, - per_document=None, - max_per_document=None, - fields=None, - count=None, - characters=None): + enabled: bool = None, + per_document: bool = None, + max_per_document: int = None, + fields: List[str] = None, + count: int = None, + characters: int = None) -> None: """ Initialize a QueryLargePassages object. :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. :param bool per_document: (optional) When `true`, passages will be returned - whithin their respective result. + within their respective result. :param int max_per_document: (optional) Maximum number of passages to return per result. - :param list[str] fields: (optional) A list of fields that passages are + :param List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int count: (optional) The maximum number of passages to return. The @@ -2413,7 +2409,7 @@ def __init__(self, self.characters = characters @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} valid_keys = [ @@ -2439,7 +2435,12 @@ def _from_dict(cls, _dict): args['characters'] = _dict.get('characters') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargePassages 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, 'enabled') and self.enabled is not None: @@ -2457,17 +2458,21 @@ def _to_dict(self): _dict['characters'] = self.characters return _dict - def __str__(self): + 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 QueryLargePassages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargePassages') -> 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): + def __ne__(self, other: 'QueryLargePassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2481,7 +2486,7 @@ class QueryLargeSuggestedRefinements(): returned. The default is `10`. The maximum is `100`. """ - def __init__(self, *, enabled=None, count=None): + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ Initialize a QueryLargeSuggestedRefinements object. @@ -2493,7 +2498,7 @@ def __init__(self, *, enabled=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} valid_keys = ['enabled', 'count'] @@ -2508,7 +2513,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeSuggestedRefinements 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, 'enabled') and self.enabled is not None: @@ -2517,17 +2527,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 QueryLargeSuggestedRefinements object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargeSuggestedRefinements') -> 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): + def __ne__(self, other: 'QueryLargeSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2540,7 +2554,7 @@ class QueryLargeTableResults(): :attr int count: (optional) Maximum number of tables to return. """ - def __init__(self, *, enabled=None, count=None): + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ Initialize a QueryLargeTableResults object. @@ -2551,7 +2565,7 @@ def __init__(self, *, enabled=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} valid_keys = ['enabled', 'count'] @@ -2566,7 +2580,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeTableResults 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, 'enabled') and self.enabled is not None: @@ -2575,129 +2594,50 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 QueryLargeTableResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargeTableResults') -> 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): + def __ne__(self, other: 'QueryLargeTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryNestedAggregation(): +class QueryNoticesResponse(): """ - A restriction that alter the document set 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 - field. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, type, path, matching_results, *, aggregations=None): - """ - Initialize a QueryNestedAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :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. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.path = path - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" - args = {} - valid_keys = ['path', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' - + ', '.join(bad_keys)) - if 'path' in _dict: - args['path'] = _dict.get('path') - else: - raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryNestedAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse(): - """ - Object containing notice query results. + Object containing 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 + :attr List[Notice] notices: (optional) Array of document results that match the query. """ - def __init__(self, *, matching_results=None, notices=None): + def __init__(self, + *, + matching_results: int = None, + notices: List['Notice'] = None) -> None: """ Initialize a QueryNoticesResponse object. :param int matching_results: (optional) The number of matching results. - :param list[Notice] notices: (optional) Array of document results that + :param List[Notice] notices: (optional) Array of document results that match the query. """ self.matching_results = matching_results self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'notices'] @@ -2714,7 +2654,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResponse 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, @@ -2724,17 +2669,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResponse') -> 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): + def __ne__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2745,44 +2694,44 @@ class QueryResponse(): :attr int matching_results: (optional) The number of matching results for the query. - :attr list[QueryResult] results: (optional) Array of document results for the + :attr List[QueryResult] results: (optional) Array of document results for the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregations for + :attr 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 **natural_language_query** value. - :attr list[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinments. - :attr list[QueryTableResult] table_results: (optional) Array of table results. + :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of + suggested refinements. + :attr List[QueryTableResult] table_results: (optional) Array of table results. """ def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - retrieval_details=None, - suggested_query=None, - suggested_refinements=None, - table_results=None): + 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) -> None: """ Initialize a QueryResponse object. :param int matching_results: (optional) The number of matching results for the query. - :param list[QueryResult] results: (optional) Array of document results for + :param List[QueryResult] results: (optional) Array of document results for the query. - :param list[QueryAggregation] aggregations: (optional) Array of + :param List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. :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. - :param list[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinments. - :param list[QueryTableResult] table_results: (optional) Array of table + :param List[QuerySuggestedRefinement] suggested_refinements: (optional) + Array of suggested refinements. + :param List[QueryTableResult] table_results: (optional) Array of table results. """ self.matching_results = matching_results @@ -2794,7 +2743,7 @@ def __init__(self, self.table_results = table_results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -2834,7 +2783,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponse 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, @@ -2859,17 +2813,21 @@ def _to_dict(self): _dict['table_results'] = [x._to_dict() for x in self.table_results] return _dict - def __str__(self): + 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 QueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResponse') -> 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): + def __ne__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2881,24 +2839,24 @@ class QueryResult(): :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 returned + :attr List[QueryResultPassage] document_passages: (optional) Passages returned by Discovery. """ def __init__(self, - document_id, - result_metadata, + document_id: str, + result_metadata: 'QueryResultMetadata', *, - metadata=None, - document_passages=None, - **kwargs): + metadata: dict = None, + document_passages: List['QueryResultPassage'] = None, + **kwargs) -> None: """ Initialize a QueryResult object. :param str document_id: The unique identifier of the document. :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. - :param list[QueryResultPassage] document_passages: (optional) Passages + :param List[QueryResultPassage] document_passages: (optional) Passages returned by Discovery. :param **kwargs: (optional) Any additional properties. """ @@ -2910,7 +2868,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -2941,7 +2899,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResult 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, 'document_id') and self.document_id is not None: @@ -2963,7 +2926,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'document_id', 'metadata', 'result_metadata', 'document_passages' } @@ -2973,17 +2940,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResult') -> 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): + def __ne__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3006,10 +2973,10 @@ class QueryResultMetadata(): """ def __init__(self, - collection_id, + collection_id: str, *, - document_retrieval_source=None, - confidence=None): + document_retrieval_source: str = None, + confidence: float = None) -> None: """ Initialize a QueryResultMetadata object. @@ -3030,7 +2997,7 @@ def __init__(self, self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} valid_keys = [ @@ -3054,7 +3021,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultMetadata 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, 'document_retrieval_source' @@ -3066,17 +3038,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 QueryResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultMetadata') -> 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): + def __ne__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3103,10 +3079,10 @@ class QueryResultPassage(): def __init__(self, *, - passage_text=None, - start_offset=None, - end_offset=None, - field=None): + passage_text: str = None, + start_offset: int = None, + end_offset: int = None, + field: str = None) -> None: """ Initialize a QueryResultPassage object. @@ -3124,7 +3100,7 @@ def __init__(self, self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} valid_keys = ['passage_text', 'start_offset', 'end_offset', 'field'] @@ -3143,7 +3119,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultPassage 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, 'passage_text') and self.passage_text is not None: @@ -3156,17 +3137,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 QueryResultPassage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultPassage') -> 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): + def __ne__(self, other: 'QueryResultPassage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3178,7 +3163,7 @@ class QuerySuggestedRefinement(): :attr str text: (optional) The text used to filter. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a QuerySuggestedRefinement object. @@ -3187,7 +3172,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -3200,24 +3185,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QuerySuggestedRefinement 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 __str__(self): + 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 QuerySuggestedRefinement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QuerySuggestedRefinement') -> 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): + def __ne__(self, other: 'QuerySuggestedRefinement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3240,12 +3234,12 @@ class QueryTableResult(): def __init__(self, *, - table_id=None, - source_document_id=None, - collection_id=None, - table_html=None, - table_html_offset=None, - table=None): + 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: """ Initialize a QueryTableResult object. @@ -3268,7 +3262,7 @@ def __init__(self, self.table = table @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} valid_keys = [ @@ -3294,7 +3288,12 @@ def _from_dict(cls, _dict): args['table'] = TableResultTable._from_dict(_dict.get('table')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTableResult 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, 'table_id') and self.table_id is not None: @@ -3314,95 +3313,21 @@ def _to_dict(self): _dict['table'] = self.table._to_dict() return _dict - def __str__(self): - """Return a `str` version of this QueryTableResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregation(): - """ - 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 list[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__(self, type, field, *, count=None, results=None): - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :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 list[QueryTermAggregationResult] results: (optional) Array of top - values for the field. - """ - self.field = field - self.count = count - self.results = results - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'count', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'results' in _dict: - args['results'] = [ - QueryTermAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this QueryTermAggregation object.""" + def __str__(self) -> str: + """Return a `str` version of this QueryTableResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTableResult') -> 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): + def __ne__(self, other: 'QueryTableResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3413,18 +3338,22 @@ class QueryTermAggregationResult(): :attr str key: Value of the field with a non-zero frequency in the document set. :attr int matching_results: Number of documents containing the 'key'. - :attr list[QueryAggregation] aggregations: (optional) An array of sub + :attr List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ - def __init__(self, key, matching_results, *, aggregations=None): + def __init__(self, + key: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryTermAggregationResult object. :param str key: Value of the field with a non-zero frequency in the document set. :param int matching_results: Number of documents containing the 'key'. - :param list[QueryAggregation] aggregations: (optional) An array of sub + :param List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ self.key = key @@ -3432,7 +3361,7 @@ def __init__(self, key, matching_results, *, aggregations=None): self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'aggregations'] @@ -3460,7 +3389,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregationResult 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, 'key') and self.key is not None: @@ -3472,143 +3406,64 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 QueryTermAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTermAggregationResult') -> 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): + def __ne__(self, other: 'QueryTermAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTimesliceAggregation(): +class QueryTimesliceAggregationResult(): """ - A specialized histogram aggregation that uses dates to create interval segments. + A timeslice interval segment. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, - hours, days, weeks, and years. - :attr list[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. + :attr 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 + in UNIX milliseconds since epoch. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - def __init__(self, type, field, interval, *, results=None): + def __init__(self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a QueryTimesliceAggregation object. + Initialize a QueryTimesliceAggregationResult object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :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. - :param list[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. + :param str key_as_string: String date value of the upper bound for the + timeslice interval in ISO-8601 format. + :param int key: Numeric date value of the upper bound for the timeslice + interval in UNIX milliseconds since epoch. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - self.field = field - self.interval = interval - self.results = results + self.key_as_string = key_as_string + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' - ) - if 'results' in _dict: - args['results'] = [ - QueryTimesliceAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict - - def __str__(self): - """Return a `str` version of this QueryTimesliceAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregationResult(): - """ - A timeslice interval segment. - - :attr 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 - in UNIX miliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the - upper bound. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, - key_as_string, - key, - matching_results, - *, - aggregations=None): - """ - Initialize a QueryTimesliceAggregationResult object. - - :param str key_as_string: String date value of the upper bound for the - timeslice interval in ISO-8601 format. - :param int key: Numeric date value of the upper bound for the timeslice - interval in UNIX miliseconds since epoch. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} valid_keys = [ @@ -3644,7 +3499,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregationResult 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, 'key_as_string') and self.key_as_string is not None: @@ -3658,83 +3518,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this QueryTimesliceAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregation(): - """ - Returns the top documents ranked by the score of the query. - - :attr int size: The number of documents to return. - :attr QueryTopHitsAggregationResult hits: (optional) - """ - - def __init__(self, type, size, *, hits=None): - """ - Initialize a QueryTopHitsAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param int size: The number of documents to return. - :param QueryTopHitsAggregationResult hits: (optional) - """ - self.size = size - self.hits = hits - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - args = {} - valid_keys = ['size', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' - + ', '.join(bad_keys)) - if 'size' in _dict: - args['size'] = _dict.get('size') - else: - raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' - ) - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult._from_dict( - _dict.get('hits')) - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this QueryTopHitsAggregation object.""" + def __str__(self) -> str: + """Return a `str` version of this QueryTimesliceAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTimesliceAggregationResult') -> 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): + def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3744,21 +3542,22 @@ class QueryTopHitsAggregationResult(): A query response containing 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. + :attr List[dict] hits: (optional) An array of the document results. """ - def __init__(self, matching_results, *, hits=None): + def __init__(self, matching_results: int, *, + hits: List[dict] = None) -> None: """ Initialize a QueryTopHitsAggregationResult object. :param int matching_results: Number of matching results. - :param list[dict] hits: (optional) An array of the document results. + :param List[dict] hits: (optional) An array of the document results. """ self.matching_results = matching_results self.hits = hits @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'hits'] @@ -3777,7 +3576,12 @@ def _from_dict(cls, _dict): args['hits'] = _dict.get('hits') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregationResult 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, @@ -3787,17 +3591,21 @@ def _to_dict(self): _dict['hits'] = self.hits return _dict - def __str__(self): + 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 QueryTopHitsAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTopHitsAggregationResult') -> 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): + def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3806,7 +3614,7 @@ class RetrievalDetails(): """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Indentifies the document + :attr 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 @@ -3814,11 +3622,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy=None): + def __init__(self, *, document_retrieval_strategy: str = None) -> None: """ Initialize a RetrievalDetails object. - :param str document_retrieval_strategy: (optional) Indentifies 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 @@ -3828,7 +3636,7 @@ def __init__(self, *, document_retrieval_strategy=None): self.document_retrieval_strategy = document_retrieval_strategy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} valid_keys = ['document_retrieval_strategy'] @@ -3842,7 +3650,12 @@ def _from_dict(cls, _dict): 'document_retrieval_strategy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' @@ -3851,23 +3664,27 @@ def _to_dict(self): 'document_retrieval_strategy'] = self.document_retrieval_strategy return _dict - def __str__(self): + 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 RetrievalDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RetrievalDetails') -> 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): + def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentRetrievalStrategyEnum(Enum): """ - Indentifies the document retrieval strategy used for this query. + 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 @@ -3896,38 +3713,40 @@ class TableBodyCells(): `column` location in the current table. :attr 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 + :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 + :attr List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row header texts. - :attr list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + :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 + :attr List[TableColumnHeaderIds] column_header_ids: (optional) A list of table column header ids. - :attr list[TableColumnHeaderTexts] column_header_texts: (optional) A list of + :attr List[TableColumnHeaderTexts] column_header_texts: (optional) A list of table column header texts. - :attr list[TableColumnHeaderTextsNormalized] column_header_texts_normalized: + :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 + :attr List[DocumentAttribute] attributes: (optional) A list of document attributes. """ def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None, - row_header_ids=None, - row_header_texts=None, - row_header_texts_normalized=None, - column_header_ids=None, - column_header_texts=None, - column_header_texts_normalized=None, - attributes=None): + 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: """ Initialize a TableBodyCells object. @@ -3946,20 +3765,20 @@ 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 + :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table row header ids. - :param list[TableRowHeaderTexts] row_header_texts: (optional) A list of + :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row header texts. - :param list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + :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 + :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of table column header ids. - :param list[TableColumnHeaderTexts] column_header_texts: (optional) A list + :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list of table column header texts. - :param list[TableColumnHeaderTextsNormalized] + :param List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: (optional) A list of table column header texts normalized. - :param list[DocumentAttribute] attributes: (optional) A list of document + :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ self.cell_id = cell_id @@ -3978,7 +3797,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} valid_keys = [ @@ -4045,7 +3864,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableBodyCells 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, 'cell_id') and self.cell_id is not None: @@ -4100,17 +3924,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 TableBodyCells object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableBodyCells') -> 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): + def __ne__(self, other: 'TableBodyCells') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4127,7 +3955,11 @@ class TableCellKey(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None) -> None: """ Initialize a TableCellKey object. @@ -4143,7 +3975,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4161,7 +3993,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellKey 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, 'cell_id') and self.cell_id is not None: @@ -4172,17 +4009,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableCellKey object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableCellKey') -> 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): + def __ne__(self, other: 'TableCellKey') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4199,7 +4040,11 @@ class TableCellValues(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None) -> None: """ Initialize a TableCellValues object. @@ -4215,7 +4060,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableCellValues': """Initialize a TableCellValues object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4233,7 +4078,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellValues 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, 'cell_id') and self.cell_id is not None: @@ -4244,17 +4094,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableCellValues object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableCellValues') -> 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): + def __ne__(self, other: 'TableCellValues') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4267,7 +4121,7 @@ class TableColumnHeaderIds(): :attr str id: (optional) The `id` value of a column header. """ - def __init__(self, *, id=None): + def __init__(self, *, id: str = None) -> None: """ Initialize a TableColumnHeaderIds object. @@ -4276,7 +4130,7 @@ def __init__(self, *, id=None): self.id = id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': """Initialize a TableColumnHeaderIds object from a json dictionary.""" args = {} valid_keys = ['id'] @@ -4289,24 +4143,33 @@ def _from_dict(cls, _dict): args['id'] = _dict.get('id') return cls(**args) - def _to_dict(self): + @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 __str__(self): + 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): + 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): + def __ne__(self, other: 'TableColumnHeaderIds') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4319,7 +4182,7 @@ class TableColumnHeaderTexts(): :attr str text: (optional) The `text` value of a column header. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a TableColumnHeaderTexts object. @@ -4328,7 +4191,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': """Initialize a TableColumnHeaderTexts object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -4341,24 +4204,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @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 __str__(self): + 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): + 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): + def __ne__(self, other: 'TableColumnHeaderTexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4372,7 +4244,7 @@ class TableColumnHeaderTextsNormalized(): text. """ - def __init__(self, *, text_normalized=None): + def __init__(self, *, text_normalized: str = None) -> None: """ Initialize a TableColumnHeaderTextsNormalized object. @@ -4382,7 +4254,7 @@ def __init__(self, *, text_normalized=None): self.text_normalized = text_normalized @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" args = {} valid_keys = ['text_normalized'] @@ -4395,7 +4267,12 @@ def _from_dict(cls, _dict): args['text_normalized'] = _dict.get('text_normalized') return cls(**args) - def _to_dict(self): + @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, @@ -4403,17 +4280,21 @@ def _to_dict(self): _dict['text_normalized'] = self.text_normalized return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4444,14 +4325,14 @@ class TableColumnHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = 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: """ Initialize a TableColumnHeaders object. @@ -4484,7 +4365,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -4514,7 +4395,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaders 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, 'cell_id') and self.cell_id is not None: @@ -4540,17 +4426,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableColumnHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableColumnHeaders') -> 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): + def __ne__(self, other: 'TableColumnHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4564,7 +4454,7 @@ class TableElementLocation(): :attr int end: The element's `end` index. """ - def __init__(self, begin, end): + def __init__(self, begin: int, end: int) -> None: """ Initialize a TableElementLocation object. @@ -4575,7 +4465,7 @@ def __init__(self, begin, end): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -4598,7 +4488,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableElementLocation 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, 'begin') and self.begin is not None: @@ -4607,17 +4502,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 TableElementLocation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableElementLocation') -> 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): + def __ne__(self, other: 'TableElementLocation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4644,13 +4543,13 @@ class TableHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = 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: """ Initialize a TableHeaders object. @@ -4679,7 +4578,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -4707,7 +4606,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableHeaders 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, 'cell_id') and self.cell_id is not None: @@ -4730,17 +4634,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableHeaders') -> 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): + def __ne__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4750,23 +4658,26 @@ 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 + :attr List[TableCellValues] value: (optional) A list of values in a key-value pair. """ - def __init__(self, *, key=None, value=None): + def __init__(self, + *, + key: 'TableCellKey' = None, + value: List['TableCellValues'] = None) -> None: """ Initialize a TableKeyValuePairs object. :param TableCellKey key: (optional) A key in a key-value pair. - :param list[TableCellValues] value: (optional) A list of values in a + :param List[TableCellValues] value: (optional) A list of values in a key-value pair. """ self.key = key self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} valid_keys = ['key', 'value'] @@ -4783,7 +4694,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableKeyValuePairs 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, 'key') and self.key is not None: @@ -4792,17 +4708,21 @@ def _to_dict(self): _dict['value'] = [x._to_dict() for x in self.value] return _dict - def __str__(self): - """Return a `str` version of this TableKeyValuePairs object.""" + 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 TableKeyValuePairs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableKeyValuePairs') -> 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): + def __ne__(self, other: 'TableKeyValuePairs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4820,35 +4740,35 @@ class TableResultTable(): within a table. :attr TableTextLocation title: (optional) Text and associated location within a table. - :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + :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, + :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 + :attr 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 + :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 + :attr 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 + :attr 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=None, - text=None, - section_title=None, - title=None, - table_headers=None, - row_headers=None, - column_headers=None, - key_value_pairs=None, - body_cells=None, - contexts=None): + 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: """ Initialize a TableResultTable object. @@ -4861,20 +4781,20 @@ def __init__(self, location within a table. :param TableTextLocation title: (optional) Text and associated location within a table. - :param list[TableHeaders] table_headers: (optional) An array of table-level + :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 + :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 + :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. - :param list[TableKeyValuePairs] key_value_pairs: (optional) An array of + :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 + :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. - :param list[TableTextLocation] contexts: (optional) An array of lists of + :param List[TableTextLocation] contexts: (optional) An array of lists of textual entries across the document related to the current table being parsed. """ @@ -4890,7 +4810,7 @@ def __init__(self, self.contexts = contexts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableResultTable': """Initialize a TableResultTable object from a json dictionary.""" args = {} valid_keys = [ @@ -4942,7 +4862,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableResultTable 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, 'location') and self.location is not None: @@ -4972,17 +4897,21 @@ def _to_dict(self): _dict['contexts'] = [x._to_dict() for x in self.contexts] return _dict - def __str__(self): + 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 TableResultTable object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableResultTable') -> 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): + def __ne__(self, other: 'TableResultTable') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4995,7 +4924,7 @@ class TableRowHeaderIds(): :attr str id: (optional) The `id` values of a row header. """ - def __init__(self, *, id=None): + def __init__(self, *, id: str = None) -> None: """ Initialize a TableRowHeaderIds object. @@ -5004,7 +4933,7 @@ def __init__(self, *, id=None): self.id = id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': """Initialize a TableRowHeaderIds object from a json dictionary.""" args = {} valid_keys = ['id'] @@ -5017,24 +4946,33 @@ def _from_dict(cls, _dict): args['id'] = _dict.get('id') return cls(**args) - def _to_dict(self): + @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 __str__(self): + 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): + 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): + def __ne__(self, other: 'TableRowHeaderIds') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5047,7 +4985,7 @@ class TableRowHeaderTexts(): :attr str text: (optional) The `text` value of a row header. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a TableRowHeaderTexts object. @@ -5056,7 +4994,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': """Initialize a TableRowHeaderTexts object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -5069,24 +5007,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @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 __str__(self): + 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): + 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): + def __ne__(self, other: 'TableRowHeaderTexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5100,7 +5047,7 @@ class TableRowHeaderTextsNormalized(): text. """ - def __init__(self, *, text_normalized=None): + def __init__(self, *, text_normalized: str = None) -> None: """ Initialize a TableRowHeaderTextsNormalized object. @@ -5110,7 +5057,7 @@ def __init__(self, *, text_normalized=None): self.text_normalized = text_normalized @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" args = {} valid_keys = ['text_normalized'] @@ -5123,7 +5070,12 @@ def _from_dict(cls, _dict): args['text_normalized'] = _dict.get('text_normalized') return cls(**args) - def _to_dict(self): + @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, @@ -5131,17 +5083,21 @@ def _to_dict(self): _dict['text_normalized'] = self.text_normalized return _dict - def __str__(self): + 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): + 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): + def __ne__(self, other: 'TableRowHeaderTextsNormalized') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5172,14 +5128,14 @@ class TableRowHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + 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: """ Initialize a TableRowHeaders object. @@ -5212,7 +5168,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5243,7 +5199,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5269,17 +5230,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableRowHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableRowHeaders') -> 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): + def __ne__(self, other: 'TableRowHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5294,7 +5259,10 @@ class TableTextLocation(): `begin` and `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, + *, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ Initialize a TableTextLocation object. @@ -5307,7 +5275,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -5323,7 +5291,12 @@ def _from_dict(cls, _dict): _dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableTextLocation 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: @@ -5332,17 +5305,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TableTextLocation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableTextLocation') -> 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): + def __ne__(self, other: 'TableTextLocation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5355,17 +5332,17 @@ class TrainingExample(): :attr str collection_id: The collection ID associated with this training example. :attr int relevance: The relevance of the training example. - :attr date created: (optional) The date and time the example was created. - :attr date updated: (optional) The date and time the example was updated. + :attr datetime created: (optional) The date and time the example was created. + :attr datetime updated: (optional) The date and time the example was updated. """ def __init__(self, - document_id, - collection_id, - relevance, + document_id: str, + collection_id: str, + relevance: int, *, - created=None, - updated=None): + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a TrainingExample object. @@ -5374,8 +5351,10 @@ def __init__(self, :param str collection_id: The collection ID associated with this training example. :param int relevance: The relevance of the training example. - :param date created: (optional) The date and time the example was created. - :param date updated: (optional) The date and time the example was updated. + :param datetime created: (optional) The date and time the example was + created. + :param datetime updated: (optional) The date and time the example was + updated. """ self.document_id = document_id self.collection_id = collection_id @@ -5384,7 +5363,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} valid_keys = [ @@ -5414,12 +5393,17 @@ def _from_dict(cls, _dict): 'Required property \'relevance\' not present in TrainingExample JSON' ) if 'created' in _dict: - args['created'] = _dict.get('created') + args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: - args['updated'] = _dict.get('updated') + args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExample 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, 'document_id') and self.document_id is not None: @@ -5429,22 +5413,26 @@ def _to_dict(self): if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created + _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = self.updated + _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 TrainingExample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExample') -> 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): + def __ne__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5457,31 +5445,33 @@ class TrainingQuery(): :attr str natural_language_query: The natural text query for the training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr date created: (optional) The date and time the query was created. - :attr date updated: (optional) The date and time the query was updated. - :attr list[TrainingExample] examples: Array of training examples. + :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, - examples, + natural_language_query: str, + examples: List['TrainingExample'], *, - query_id=None, - filter=None, - created=None, - updated=None): + query_id: str = None, + filter: str = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a TrainingQuery object. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :param List[TrainingExample] examples: Array of training examples. :param str query_id: (optional) The query ID associated with the training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param date created: (optional) The date and time the query was created. - :param date updated: (optional) The date and time the query was updated. + :param datetime created: (optional) The date and time the query was + created. + :param datetime updated: (optional) The date and time the query was + updated. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -5491,7 +5481,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} valid_keys = [ @@ -5514,9 +5504,9 @@ def _from_dict(cls, _dict): if 'filter' in _dict: args['filter'] = _dict.get('filter') if 'created' in _dict: - args['created'] = _dict.get('created') + args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: - args['updated'] = _dict.get('updated') + args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) @@ -5527,7 +5517,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuery 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, 'query_id') and self.query_id is not None: @@ -5538,24 +5533,28 @@ def _to_dict(self): if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created + _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = self.updated + _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingQuery object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuery') -> 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): + def __ne__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5564,19 +5563,19 @@ class TrainingQuerySet(): """ Object specifying the training queries contained in the identified training set. - :attr list[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. """ - def __init__(self, *, queries=None): + def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: """ Initialize a TrainingQuerySet object. - :param list[TrainingQuery] queries: (optional) Array of training queries. + :param List[TrainingQuery] queries: (optional) Array of training queries. """ self.queries = queries @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': """Initialize a TrainingQuerySet object from a json dictionary.""" args = {} valid_keys = ['queries'] @@ -5591,23 +5590,734 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuerySet 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, 'queries') and self.queries is not None: _dict['queries'] = [x._to_dict() for x in self.queries] return _dict - def __str__(self): + 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 TrainingQuerySet object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuerySet') -> 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: 'TrainingQuerySet') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +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. + """ + + def __init__(self, type: str, field: str, *, value: float = None) -> None: + """ + Initialize a QueryCalculationAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. + """ + self.type = type + self.field = field + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': + """Initialize a QueryCalculationAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryCalculationAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryCalculationAggregation JSON' + ) + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryCalculationAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + 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 QueryCalculationAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryCalculationAggregation') -> 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: 'QueryCalculationAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryFilterAggregation(QueryAggregation): + """ + A modifier that will narrow down the document set of the sub aggregations it precedes. + + :attr str match: The filter written in Discovery Query Language syntax applied + to the documents before sub aggregations are run. + :attr int matching_results: Number of documents matching the filter. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + type: str, + match: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryFilterAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str match: The filter written in Discovery Query Language syntax + applied to the documents before sub aggregations are run. + :param int matching_results: Number of documents matching the filter. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.type = type + self.match = match + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': + """Initialize a QueryFilterAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'match', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryFilterAggregation JSON' + ) + if 'match' in _dict: + args['match'] = _dict.get('match') + else: + raise ValueError( + 'Required property \'match\' not present in QueryFilterAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryFilterAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 QueryFilterAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryFilterAggregation') -> 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: 'QueryFilterAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +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 the results are split into. + :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric + intervals. + """ + + def __init__(self, + type: str, + field: str, + interval: int, + *, + results: List['QueryHistogramAggregationResult'] = None + ) -> None: + """ + Initialize a QueryHistogramAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections the results are split into. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. + """ + self.type = type + self.field = field + self.interval = interval + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': + """Initialize a QueryHistogramAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryHistogramAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryHistogramAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryHistogramAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryHistogramAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryHistogramAggregation') -> 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: 'QueryHistogramAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryNestedAggregation(QueryAggregation): + """ + A restriction that alter the document set 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 + field. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + type: str, + path: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryNestedAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :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. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.type = type + self.path = path + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': + """Initialize a QueryNestedAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'path', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryNestedAggregation JSON' + ) + if 'path' in _dict: + args['path'] = _dict.get('path') + else: + raise ValueError( + 'Required property \'path\' not present in QueryNestedAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNestedAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 QueryNestedAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryNestedAggregation') -> 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: 'QueryNestedAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +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 List[QueryTermAggregationResult] results: (optional) Array of top values + for the field. + """ + + def __init__(self, + type: str, + field: str, + *, + count: int = None, + results: List['QueryTermAggregationResult'] = None) -> None: + """ + Initialize a QueryTermAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :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 List[QueryTermAggregationResult] results: (optional) Array of top + values for the field. + """ + self.type = type + self.field = field + self.count = count + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': + """Initialize a QueryTermAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'count', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTermAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTermAggregation JSON' + ) + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'results' in _dict: + args['results'] = [ + QueryTermAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryTermAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTermAggregation') -> 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: 'QueryTermAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +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, + hours, days, weeks, and years. + :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + + def __init__(self, + type: str, + field: str, + interval: str, + *, + results: List['QueryTimesliceAggregationResult'] = None + ) -> None: + """ + Initialize a QueryTimesliceAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :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. + :param List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + self.type = type + self.field = field + self.interval = interval + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': + """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTimesliceAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryTimesliceAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryTimesliceAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTimesliceAggregation') -> 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: 'QueryTimesliceAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregation(QueryAggregation): + """ + Returns the top documents ranked by the score of the query. + + :attr int size: The number of documents to return. + :attr QueryTopHitsAggregationResult hits: (optional) + """ + + def __init__(self, + type: str, + size: int, + *, + hits: 'QueryTopHitsAggregationResult' = None) -> None: + """ + Initialize a QueryTopHitsAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param int size: The number of documents to return. + :param QueryTopHitsAggregationResult hits: (optional) + """ + self.type = type + self.size = size + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': + """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'size', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTopHitsAggregation JSON' + ) + if 'size' in _dict: + args['size'] = _dict.get('size') + else: + raise ValueError( + 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + ) + if 'hits' in _dict: + args['hits'] = QueryTopHitsAggregationResult._from_dict( + _dict.get('hits')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregation 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, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'size') and self.size is not None: + _dict['size'] = self.size + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits._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 QueryTopHitsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopHitsAggregation') -> 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): + def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index da2d2caad..fedc9e9bd 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,10 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses import tempfile +import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * base_url = 'https://fake' @@ -26,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_collections #----------------------------------------------------------------------------- @@ -58,8 +61,7 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, - fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -73,14 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -106,7 +110,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -152,14 +155,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -167,39 +172,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "collection_ids": [], - "filter": - "string1", - "query": - "string1", - "natural_language_query": - "string1", - "aggregation": - "string1", - "count": - 12345, - "return_": [], - "offset": - 12345, - "sort": - "string1", - "highlight": - True, - "spelling_suggestions": - True, - "table_results": - QueryLargeTableResults._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "suggested_refinements": - QueryLargeSuggestedRefinements._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "passages": - QueryLargePassages._from_dict( - json.loads( - """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" - )), - }) + body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) return body def construct_required_body(self): @@ -253,14 +226,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -312,8 +287,7 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, - fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -327,14 +301,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -400,14 +376,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -434,7 +412,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for get_component_settings #----------------------------------------------------------------------------- @@ -466,8 +443,7 @@ def test_get_component_settings_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_component_settings_empty(self): - check_empty_required_params( - self, fake_response_ComponentSettingsResponse_json) + check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -475,21 +451,22 @@ def test_get_component_settings_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/component_settings'.format(body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -515,7 +492,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -555,21 +531,22 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( - body['project_id'], body['collection_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -631,21 +608,22 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -701,8 +679,7 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, - fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -710,21 +687,22 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -755,7 +733,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_training_queries #----------------------------------------------------------------------------- @@ -795,21 +772,22 @@ def test_list_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -864,21 +842,22 @@ def test_delete_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -933,21 +912,22 @@ def test_create_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -955,20 +935,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1011,21 +984,22 @@ def test_get_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1082,21 +1056,22 @@ def test_update_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1105,22 +1080,14 @@ def construct_full_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1146,7 +1113,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1163,7 +1129,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1175,7 +1140,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1192,7 +1156,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### @@ -1208,6 +1171,6 @@ def send_request(obj, body, response, url=None): fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" fake_response_TrainingQuerySet_json = """{"queries": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" From 935fd7a8bf932ded30b063b898fa151e5bd12291 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 15:34:02 -0500 Subject: [PATCH 08/28] refactor(ltv3): regenrate language translate v3 with tests --- ibm_watson/language_translator_v3.py | 540 +++++---- test/unit/test_language_translator_v3.py | 1334 ++++++++++++++++------ 2 files changed, 1302 insertions(+), 572 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 9b0612b73..39c70bf37 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. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -38,13 +45,15 @@ class LanguageTranslatorV3(BaseService): """The Language Translator V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_NAME = 'language_translator' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Language Translator service. @@ -63,43 +72,32 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('language_translator') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'language_translator') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Translation ######################### def translate(self, - text, + text: List[str], *, - model_id=None, - source=None, - target=None, - **kwargs): + model_id: str = None, + source: str = None, + target: str = None, + **kwargs) -> 'DetailedResponse': """ Translate. Translates the input text from the source language to the target language. - :param list[str] text: Input text in UTF-8 encoding. Multiple entries will + :param List[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. :param str model_id: (optional) A globally unique string that identifies the underlying model that is used for translation. @@ -116,7 +114,9 @@ def translate(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', 'translate') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate') headers.update(sdk_headers) params = {'version': self.version} @@ -133,8 +133,8 @@ def translate(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -142,7 +142,7 @@ def translate(self, # Identification ######################### - def list_identifiable_languages(self, **kwargs): + def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': """ List identifiable languages. @@ -157,8 +157,10 @@ def list_identifiable_languages(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'list_identifiable_languages') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_identifiable_languages') headers.update(sdk_headers) params = {'version': self.version} @@ -167,12 +169,12 @@ def list_identifiable_languages(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def identify(self, text, **kwargs): + def identify(self, text: str, **kwargs) -> 'DetailedResponse': """ Identify language. @@ -190,7 +192,9 @@ def identify(self, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', 'identify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='identify') headers.update(sdk_headers) params = {'version': self.version} @@ -203,8 +207,8 @@ def identify(self, text, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -212,7 +216,12 @@ def identify(self, text, **kwargs): # Models ######################### - def list_models(self, *, source=None, target=None, default=None, **kwargs): + def list_models(self, + *, + source: str = None, + target: str = None, + default: bool = None, + **kwargs) -> 'DetailedResponse': """ List models. @@ -235,8 +244,9 @@ def list_models(self, *, source=None, target=None, default=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = { @@ -250,18 +260,18 @@ def list_models(self, *, source=None, target=None, default=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_model(self, - base_model_id, + base_model_id: str, *, - forced_glossary=None, - parallel_corpus=None, - name=None, - **kwargs): + forced_glossary: BinaryIO = None, + parallel_corpus: BinaryIO = None, + name: str = None, + **kwargs) -> 'DetailedResponse': """ Create model. @@ -284,17 +294,17 @@ def create_model(self, Usually all IBM provided models are customizable. In addition, all your models that have been created via parallel corpus customization, can be further customized with a forced glossary. - :param file forced_glossary: (optional) A TMX file with your + :param TextIO forced_glossary: (optional) A TMX file with your customizations. The customizations in the file completely overwrite the domain translaton data, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain single words or short phrases. - :param file parallel_corpus: (optional) A TMX file with parallel sentences - for source and target language. You can upload multiple parallel_corpus - files in one request. All uploaded parallel_corpus files combined, your - parallel corpus must contain at least 5,000 parallel sentences to train - successfully. + :param TextIO parallel_corpus: (optional) A TMX file with parallel + sentences for source and target language. You can upload multiple + parallel_corpus files in one request. All uploaded parallel_corpus files + combined, your parallel corpus must contain at least 5,000 parallel + sentences to train successfully. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. @@ -309,8 +319,9 @@ def create_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = { @@ -332,12 +343,12 @@ def create_model(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_model(self, model_id, **kwargs): + def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Delete model. @@ -355,8 +366,9 @@ def delete_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} @@ -365,12 +377,12 @@ def delete_model(self, model_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_model(self, model_id, **kwargs): + def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Get model details. @@ -390,7 +402,9 @@ def get_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', '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 = {'version': self.version} @@ -399,8 +413,8 @@ def get_model(self, model_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -408,7 +422,7 @@ def get_model(self, model_id, **kwargs): # Document translation ######################### - def list_documents(self, **kwargs): + def list_documents(self, **kwargs) -> 'DetailedResponse': """ List documents. @@ -422,8 +436,9 @@ def list_documents(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} @@ -432,21 +447,21 @@ def list_documents(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def translate_document(self, - file, + file: BinaryIO, *, - filename=None, - file_content_type=None, - model_id=None, - source=None, - target=None, - document_id=None, - **kwargs): + filename: str = None, + file_content_type: str = None, + model_id: str = None, + source: str = None, + target: str = None, + document_id: str = None, + **kwargs) -> 'DetailedResponse': """ Translate document. @@ -454,7 +469,7 @@ def translate_document(self, `file` parameter, or you can reference a previously submitted document by document ID. - :param file file: The source file to translate. + :param TextIO file: The contents of the source file to translate. [Supported file types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) Maximum file size: **20 MB**. @@ -480,8 +495,9 @@ def translate_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} @@ -494,12 +510,16 @@ def translate_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if model_id: + model_id = str(model_id) form_data.append(('model_id', (None, model_id, 'text/plain'))) if source: + source = str(source) form_data.append(('source', (None, source, 'text/plain'))) if target: + target = str(target) form_data.append(('target', (None, target, 'text/plain'))) if document_id: + document_id = str(document_id) form_data.append(('document_id', (None, document_id, 'text/plain'))) url = '/v3/documents' @@ -507,12 +527,13 @@ def translate_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_document_status(self, document_id, **kwargs): + def get_document_status(self, document_id: str, + **kwargs) -> 'DetailedResponse': """ Get document status. @@ -530,8 +551,9 @@ def get_document_status(self, document_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} @@ -540,12 +562,12 @@ def get_document_status(self, document_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_document(self, document_id, **kwargs): + def delete_document(self, document_id: str, **kwargs) -> 'DetailedResponse': """ Delete document. @@ -563,8 +585,9 @@ def delete_document(self, document_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} @@ -573,12 +596,16 @@ def delete_document(self, document_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_translated_document(self, document_id, *, accept=None, **kwargs): + def get_translated_document(self, + document_id: str, + *, + accept: str = None, + **kwargs) -> 'DetailedResponse': """ Get translated document. @@ -611,20 +638,20 @@ def get_translated_document(self, document_id, *, accept=None, **kwargs): headers = {'Accept': accept} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - '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 = {'version': self.version} url = '/v3/documents/{0}/translated_document'.format( *self._encode_path_vars(document_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=(accept is None or accept == 'application/json')) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + response = self.send(request) return response @@ -713,7 +740,7 @@ class DeleteModelResult(): :attr str status: "OK" indicates that the model was successfully deleted. """ - def __init__(self, status): + def __init__(self, status: str) -> None: """ Initialize a DeleteModelResult object. @@ -722,7 +749,7 @@ def __init__(self, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': """Initialize a DeleteModelResult object from a json dictionary.""" args = {} valid_keys = ['status'] @@ -739,24 +766,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteModelResult 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, 'status') and self.status is not None: _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteModelResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteModelResult') -> 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): + def __ne__(self, other: 'DeleteModelResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -765,21 +801,21 @@ class DocumentList(): """ DocumentList. - :attr list[DocumentStatus] documents: An array of all previously submitted + :attr List[DocumentStatus] documents: An array of all previously submitted documents. """ - def __init__(self, documents): + def __init__(self, documents: List['DocumentStatus']) -> None: """ Initialize a DocumentList object. - :param list[DocumentStatus] documents: An array of all previously submitted + :param List[DocumentStatus] documents: An array of all previously submitted documents. """ self.documents = documents @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentList': """Initialize a DocumentList object from a json dictionary.""" args = {} valid_keys = ['documents'] @@ -798,24 +834,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentList 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, 'documents') and self.documents is not None: _dict['documents'] = [x._to_dict() for x in self.documents] return _dict - def __str__(self): + 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 DocumentList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentList') -> 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): + def __ne__(self, other: 'DocumentList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -839,25 +884,25 @@ class DocumentStatus(): :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) The number of words in the source document, - present only if status=available. + :attr 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 document, present only if status=available. """ def __init__(self, - document_id, - filename, - status, - model_id, - source, - target, - created, + document_id: str, + filename: str, + status: str, + model_id: str, + source: str, + target: str, + created: datetime, *, - base_model_id=None, - completed=None, - word_count=None, - character_count=None): + base_model_id: str = None, + completed: datetime = None, + word_count: int = None, + character_count: int = None) -> None: """ Initialize a DocumentStatus object. @@ -877,8 +922,8 @@ def __init__(self, be absent or an empty string. :param datetime completed: (optional) The time when the translation completed. - :param int word_count: (optional) The number of words in the source - document, present only if status=available. + :param int word_count: (optional) An estimate of the number of words in the + source document. Returned only if `status` is `available`. :param int character_count: (optional) The number of characters in the source document, present only if status=available. """ @@ -895,7 +940,7 @@ def __init__(self, self.character_count = character_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -960,7 +1005,12 @@ def _from_dict(cls, _dict): args['character_count'] = _dict.get('character_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentStatus 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, 'document_id') and self.document_id is not None: @@ -988,17 +1038,21 @@ def _to_dict(self): _dict['character_count'] = self.character_count return _dict - def __str__(self): + 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 DocumentStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentStatus') -> 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): + def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1019,7 +1073,7 @@ class IdentifiableLanguage(): :attr str name: The name of the identifiable language. """ - def __init__(self, language, name): + def __init__(self, language: str, name: str) -> None: """ Initialize a IdentifiableLanguage object. @@ -1030,7 +1084,7 @@ def __init__(self, language, name): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} valid_keys = ['language', 'name'] @@ -1053,7 +1107,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiableLanguage 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, 'language') and self.language is not None: @@ -1062,17 +1121,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 IdentifiableLanguage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiableLanguage') -> 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): + def __ne__(self, other: 'IdentifiableLanguage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1081,21 +1144,21 @@ class IdentifiableLanguages(): """ IdentifiableLanguages. - :attr list[IdentifiableLanguage] languages: A list of all languages that the + :attr List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ - def __init__(self, languages): + def __init__(self, languages: List['IdentifiableLanguage']) -> None: """ Initialize a IdentifiableLanguages object. - :param list[IdentifiableLanguage] languages: A list of all languages that + :param List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ self.languages = languages @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} valid_keys = ['languages'] @@ -1115,24 +1178,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiableLanguages 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, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict - def __str__(self): + 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 IdentifiableLanguages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiableLanguages') -> 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): + def __ne__(self, other: 'IdentifiableLanguages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1145,7 +1217,7 @@ class IdentifiedLanguage(): :attr float confidence: The confidence score for the identified language. """ - def __init__(self, language, confidence): + def __init__(self, language: str, confidence: float) -> None: """ Initialize a IdentifiedLanguage object. @@ -1156,7 +1228,7 @@ def __init__(self, language, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} valid_keys = ['language', 'confidence'] @@ -1179,7 +1251,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiedLanguage 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, 'language') and self.language is not None: @@ -1188,17 +1265,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 IdentifiedLanguage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiedLanguage') -> 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): + def __ne__(self, other: 'IdentifiedLanguage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1207,21 +1288,21 @@ class IdentifiedLanguages(): """ IdentifiedLanguages. - :attr list[IdentifiedLanguage] languages: A ranking of identified languages with + :attr List[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ - def __init__(self, languages): + def __init__(self, languages: List['IdentifiedLanguage']) -> None: """ Initialize a IdentifiedLanguages object. - :param list[IdentifiedLanguage] languages: A ranking of identified + :param List[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ self.languages = languages @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} valid_keys = ['languages'] @@ -1241,24 +1322,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiedLanguages 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, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict - def __str__(self): + 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 IdentifiedLanguages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiedLanguages') -> 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): + def __ne__(self, other: 'IdentifiedLanguages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1270,7 +1360,7 @@ class Translation(): :attr str translation: Translation output in UTF-8. """ - def __init__(self, translation): + def __init__(self, translation: str) -> None: """ Initialize a Translation object. @@ -1279,7 +1369,7 @@ def __init__(self, translation): self.translation = translation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} valid_keys = ['translation'] @@ -1296,24 +1386,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Translation 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, 'translation') and self.translation is not None: _dict['translation'] = self.translation return _dict - def __str__(self): + 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 Translation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Translation') -> 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): + def __ne__(self, other: 'Translation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1344,17 +1443,17 @@ class TranslationModel(): """ def __init__(self, - model_id, + model_id: str, *, - name=None, - source=None, - target=None, - base_model_id=None, - domain=None, - customizable=None, - default_model=None, - owner=None, - status=None): + 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: """ Initialize a TranslationModel object. @@ -1392,7 +1491,7 @@ def __init__(self, self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationModel': """Initialize a TranslationModel object from a json dictionary.""" args = {} valid_keys = [ @@ -1430,7 +1529,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationModel 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, 'model_id') and self.model_id is not None: @@ -1455,17 +1559,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 TranslationModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationModel') -> 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): + def __ne__(self, other: 'TranslationModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1489,19 +1597,19 @@ class TranslationModels(): """ The response type for listing existing translation models. - :attr list[TranslationModel] models: An array of available models. + :attr List[TranslationModel] models: An array of available models. """ - def __init__(self, models): + def __init__(self, models: List['TranslationModel']) -> None: """ Initialize a TranslationModels object. - :param list[TranslationModel] models: An array of available models. + :param List[TranslationModel] models: An array of available models. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationModels': """Initialize a TranslationModels object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -1520,24 +1628,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationModels 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 TranslationModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationModels') -> 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): + def __ne__(self, other: 'TranslationModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1546,19 +1663,21 @@ class TranslationResult(): """ TranslationResult. - :attr int word_count: Number of words in the input text. + :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 list[Translation] translations: List of translation output in UTF-8, + :attr List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ - def __init__(self, word_count, character_count, translations): + def __init__(self, word_count: int, character_count: int, + translations: List['Translation']) -> None: """ Initialize a TranslationResult object. - :param int word_count: Number of words in the input text. + :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 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. """ self.word_count = word_count @@ -1566,7 +1685,7 @@ def __init__(self, word_count, character_count, translations): self.translations = translations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} valid_keys = ['word_count', 'character_count', 'translations'] @@ -1597,7 +1716,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationResult 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, 'word_count') and self.word_count is not None: @@ -1609,16 +1733,20 @@ def _to_dict(self): _dict['translations'] = [x._to_dict() for x in self.translations] return _dict - def __str__(self): + 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 TranslationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationResult') -> 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): + def __ne__(self, other: 'TranslationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index a46144287..54f08512e 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,385 +1,987 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import time -import jwt -from unittest import TestCase -from os.path import join, dirname -import ibm_watson -from ibm_watson.language_translator_v3 import TranslationResult, TranslationModels, TranslationModel, IdentifiedLanguages, IdentifiableLanguages, DeleteModelResult -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/language-translator/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestLanguageTranslatorV3(TestCase): - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add( - responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @classmethod - @responses.activate - def test_translate_source_target(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) +import tempfile +import ibm_watson.language_translator_v3 +from ibm_watson.language_translator_v3 import * + +base_url = 'https://gateway.watsonplatform.net/language-translator/api' + +############################################################################## +# Start of Service: Translation +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for translate +#----------------------------------------------------------------------------- +class TestTranslate(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_response(self): + body = self.construct_full_body() + response = fake_response_TranslationResult_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationResult_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_empty(self): + check_empty_required_params(self, fake_response_TranslationResult_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/translate' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "character_count": 19, - "translations": [{"translation": u"Hello, how are you ? \u20ac"}], - "word_count": 4 - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - - response = service.translate('Hola, cómo estás? €', source='es', target='en').get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationResult._from_dict(response) - - @classmethod - @responses.activate - def test_translate_model_id(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/translate' + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.translate(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + return body + + +# endregion +############################################################################## +# End of Service: Translation +############################################################################## + +############################################################################## +# Start of Service: Identification +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_identifiable_languages +#----------------------------------------------------------------------------- +class TestListIdentifiableLanguages(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_identifiable_languages_response(self): + body = self.construct_full_body() + response = fake_response_IdentifiableLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_identifiable_languages_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IdentifiableLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_identifiable_languages_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/identifiable_languages' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "character_count": 22, - "translations": [ - { - "translation": "Messi es el mejor" - } - ], - "word_count": 5 - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.translate('Messi is the best ever', - model_id='en-es-conversational').get_result() - - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationResult._from_dict(response) - - @classmethod - @responses.activate - def test_identify(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_identifiable_languages(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for identify +#----------------------------------------------------------------------------- +class TestIdentify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_identify_response(self): + body = self.construct_full_body() + response = fake_response_IdentifiedLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_identify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IdentifiedLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_identify_empty(self): + check_empty_required_params(self, fake_response_IdentifiedLanguages_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/identify' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "languages": [ - { - "confidence": 0.477673, - "language": "zh" - }, - { - "confidence": 0.262053, - "language": "zh-TW" - }, - { - "confidence": 0.00958378, - "language": "en" - } - ] - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.identify('祝你有美好的一天').get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - IdentifiedLanguages._from_dict(response) - - @classmethod - @responses.activate - def test_list_identifiable_languages(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/identifiable_languages' + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.identify(**body) + return output + + def construct_full_body(self): + body = dict() + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Identification +############################################################################## + +############################################################################## +# Start of Service: Models +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "languages": [ - { - "name": "German", - "language": "de" - }, - { - "name": "Greek", - "language": "el" - }, - { - "name": "English", - "language": "en" - }, - { - "name": "Esperanto", - "language": "eo" - }, - { - "name": "Spanish", - "language": "es" - }, - { - "name": "Chinese", - "language": "zh" - } - ] - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.list_identifiable_languages().get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - IdentifiableLanguages._from_dict(response) - - @classmethod - @responses.activate - def test_create_model(cls): - authenticator = BasicAuthenticator('xxx', 'yyy') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['source'] = "string1" + body['target'] = "string1" + body['default'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_model +#----------------------------------------------------------------------------- +class TestCreateModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_model_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_model_empty(self): + check_empty_required_params(self, fake_response_TranslationModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "en-es-conversational", - "owner": "", - "default_model": False, - "name": "test_glossary" - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - with open(join(dirname(__file__), '../../resources/language_translator_model.tmx'), 'rb') as custom_model: - response = service.create_model('en-fr', - name='test_glossary', - forced_glossary=custom_model).get_result() + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.create_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['base_model_id'] = "string1" + body['forced_glossary'] = tempfile.NamedTemporaryFile() + body['parallel_corpus'] = tempfile.NamedTemporaryFile() + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['base_model_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_model +#----------------------------------------------------------------------------- +class TestDeleteModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_response(self): + body = self.construct_full_body() + response = fake_response_DeleteModelResult_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteModelResult_json + send_request(self, body, response) assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert response == expected - TranslationModel._from_dict(response) - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_model(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - model_id = 'en-es-conversational' - endpoint = '/v3/models/' + model_id + def test_delete_model_empty(self): + check_empty_required_params(self, fake_response_DeleteModelResult_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models/{0}'.format(body['model_id']) url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "OK", - } - responses.add( - responses.DELETE, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.delete_model(model_id).get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - DeleteModelResult._from_dict(response) - - @classmethod - @responses.activate - def test_get_model(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - model_id = 'en-es-conversational' - endpoint = '/v3/models/' + model_id + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.delete_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_model +#----------------------------------------------------------------------------- +class TestGetModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_empty(self): + check_empty_required_params(self, fake_response_TranslationModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models/{0}'.format(body['model_id']) url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "", - "owner": "", - "default_model": False, - "name": "en-es-conversational" - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.get_model(model_id).get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationModel._from_dict(response) - - @classmethod - @responses.activate - def test_list_models(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/models' + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Models +############################################################################## + +############################################################################## +# Start of Service: DocumentTranslation +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_documents +#----------------------------------------------------------------------------- +class TestListDocuments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_documents_response(self): + body = self.construct_full_body() + response = fake_response_DocumentList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_documents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_documents_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "models": [ - { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "", - "owner": "", - "default_model": False, - "name": "en-es-conversational" - }, - { - "status": "available", - "model_id": "es-en", - "domain": "news", - "target": "en", - "customizable": True, - "source": "es", - "base_model_id": "", - "owner": "", - "default_model": True, - "name": "es-en" - } - ] - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.list_models().get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationModels._from_dict(response) - - @classmethod - @responses.activate - def test_document_translation(cls): - document_status = { - 'status': 'processing', - 'model_id': 'en-es', - 'target': 'es', - 'created': '2019-06-05T20:59:37', - 'filename': 'hello_world.txt', - 'source': 'en', - 'document_id': '2a683723'} + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_documents(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for translate_document +#----------------------------------------------------------------------------- +class TestTranslateDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_document_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/documents' url = '{0}{1}'.format(base_url, endpoint) - responses.add( - responses.POST, - url, - body=json.dumps(document_status), - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - url + '/2a683723', - status=200) - responses.add( - responses.GET, - url, - body=json.dumps({'documents': [document_status]}), - status=200, - content_type='application_json') - responses.add( - responses.GET, - url + '/2a683723/translated_document?version=2018-05-01', - body='binary response', - status=200) - responses.add( - responses.GET, - url + '/2a683723?version=2018-05-01', - body=json.dumps(document_status), - status=200, - content_type='application_json') - authenticator = BasicAuthenticator('xxx', 'yyy') - language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - - with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: - translation = language_translator.translate_document( - file=fileinfo, - file_content_type='text/plain', - model_id='en-es').get_result() - assert translation == document_status - - status = language_translator.list_documents().get_result() - assert status['documents'][0]['document_id'] == '2a683723' - - delete_result = language_translator.delete_document('2a683723').get_result() - assert delete_result is None - - response = language_translator.get_translated_document('2a683723', accept='text/plain').get_result() - assert response.content is not None - - doc_status = language_translator.get_document_status('2a683723').get_result() - assert doc_status['document_id'] == '2a683723' - - assert len(responses.calls) == 5 + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.translate_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['model_id'] = "string1" + body['source'] = "string1" + body['target'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_document_status +#----------------------------------------------------------------------------- +class TestGetDocumentStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents/{0}'.format(body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_document_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_document +#----------------------------------------------------------------------------- +class TestDeleteDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents/{0}'.format(body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.delete_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_translated_document +#----------------------------------------------------------------------------- +class TestGetTranslatedDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_translated_document_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_translated_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_translated_document_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents/{0}/translated_document'.format(body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_translated_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + body['accept'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: DocumentTranslation +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "translations": []}""" +fake_response_IdentifiableLanguages_json = """{"languages": []}""" +fake_response_IdentifiedLanguages_json = """{"languages": []}""" +fake_response_TranslationModels_json = """{"models": []}""" +fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" +fake_response_DeleteModelResult_json = """{"status": "fake_status"}""" +fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" +fake_response_DocumentList_json = """{"documents": []}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" From 22df14a53bef7182a8061179e0e5af230d697edc Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:32:03 -0500 Subject: [PATCH 09/28] refactor(nlc): regenerate natural language classifier with tests --- ibm_watson/natural_language_classifier_v1.py | 314 +++++--- .../test_natural_language_classifier_v1.py | 678 ++++++++++++++---- 2 files changed, 740 insertions(+), 252 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 2f7a00d05..2b7ffd4a6 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,12 +21,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -36,12 +44,14 @@ class NaturalLanguageClassifierV1(BaseService): """The Natural Language Classifier V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_NAME = 'natural_language_classifier' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Natural Language Classifier service. @@ -49,30 +59,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('natural_language_classifier') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'natural_language_classifier') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Classify text ######################### - def classify(self, classifier_id, text, **kwargs): + def classify(self, classifier_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Classify a phrase. @@ -95,8 +95,9 @@ def classify(self, classifier_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'classify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify') headers.update(sdk_headers) data = {'text': text} @@ -106,12 +107,14 @@ def classify(self, classifier_id, text, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def classify_collection(self, classifier_id, collection, **kwargs): + def classify_collection(self, classifier_id: str, + collection: List['ClassifyInput'], + **kwargs) -> 'DetailedResponse': """ Classify multiple phrases. @@ -120,7 +123,7 @@ def classify_collection(self, classifier_id, collection, **kwargs): Note that classifying Japanese texts is a beta feature. :param str classifier_id: Classifier ID to use. - :param list[ClassifyInput] collection: The submitted phrases. + :param List[ClassifyInput] collection: The submitted phrases. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -135,8 +138,9 @@ def classify_collection(self, classifier_id, collection, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'classify_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify_collection') headers.update(sdk_headers) data = {'collection': collection} @@ -146,8 +150,8 @@ def classify_collection(self, classifier_id, collection, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -155,21 +159,23 @@ def classify_collection(self, classifier_id, collection, **kwargs): # Manage classifiers ######################### - def create_classifier(self, training_metadata, training_data, **kwargs): + def create_classifier(self, training_metadata: BinaryIO, + training_data: BinaryIO, + **kwargs) -> 'DetailedResponse': """ Create classifier. Sends data to create and train a classifier and returns information about the new classifier. - :param file training_metadata: Metadata in JSON format. The metadata + :param TextIO training_metadata: Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). - :param file training_data: Training data in CSV format. Each text value + :param TextIO training_data: Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see [Data preparation](https://cloud.ibm.com/docs/services/natural-language-classifier?topic=natural-language-classifier-using-your-data). @@ -186,8 +192,9 @@ def create_classifier(self, training_metadata, training_data, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'create_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_classifier') headers.update(sdk_headers) form_data = [] @@ -199,12 +206,12 @@ def create_classifier(self, training_metadata, training_data, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_classifiers(self, **kwargs): + def list_classifiers(self, **kwargs) -> 'DetailedResponse': """ List classifiers. @@ -218,19 +225,19 @@ def list_classifiers(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'list_classifiers') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_classifiers') headers.update(sdk_headers) url = '/v1/classifiers' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_classifier(self, classifier_id, **kwargs): + def get_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Get information about a classifier. @@ -248,20 +255,20 @@ def get_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'get_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifier') headers.update(sdk_headers) url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_classifier(self, classifier_id, **kwargs): + def delete_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Delete classifier. @@ -277,16 +284,17 @@ def delete_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'delete_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_classifier') headers.update(sdk_headers) url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -304,17 +312,17 @@ class Classification(): :attr str url: (optional) Link to the classifier. :attr str text: (optional) The submitted phrase. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten + :attr List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ def __init__(self, *, - classifier_id=None, - url=None, - text=None, - top_class=None, - classes=None): + classifier_id: str = None, + url: str = None, + text: str = None, + top_class: str = None, + classes: List['ClassifiedClass'] = None) -> None: """ Initialize a Classification object. @@ -322,7 +330,7 @@ def __init__(self, :param str url: (optional) Link to the classifier. :param str text: (optional) The submitted phrase. :param str top_class: (optional) The class with the highest confidence. - :param list[ClassifiedClass] classes: (optional) An array of up to ten + :param List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.classifier_id = classifier_id @@ -332,7 +340,7 @@ def __init__(self, self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classification': """Initialize a Classification object from a json dictionary.""" args = {} valid_keys = ['classifier_id', 'url', 'text', 'top_class', 'classes'] @@ -355,7 +363,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classification 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, 'classifier_id') and self.classifier_id is not None: @@ -370,17 +383,21 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 Classification object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classification') -> 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): + def __ne__(self, other: 'Classification') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -391,17 +408,21 @@ class ClassificationCollection(): :attr str classifier_id: (optional) Unique identifier for this classifier. :attr str url: (optional) Link to the classifier. - :attr list[CollectionItem] collection: (optional) An array of classifier + :attr List[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ - def __init__(self, *, classifier_id=None, url=None, collection=None): + def __init__(self, + *, + classifier_id: str = None, + url: str = None, + collection: List['CollectionItem'] = None) -> None: """ Initialize a ClassificationCollection object. :param str classifier_id: (optional) Unique identifier for this classifier. :param str url: (optional) Link to the classifier. - :param list[CollectionItem] collection: (optional) An array of classifier + :param List[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ self.classifier_id = classifier_id @@ -409,7 +430,7 @@ def __init__(self, *, classifier_id=None, url=None, collection=None): self.collection = collection @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassificationCollection': """Initialize a ClassificationCollection object from a json dictionary.""" args = {} valid_keys = ['classifier_id', 'url', 'collection'] @@ -428,7 +449,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassificationCollection 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, 'classifier_id') and self.classifier_id is not None: @@ -439,17 +465,21 @@ def _to_dict(self): _dict['collection'] = [x._to_dict() for x in self.collection] return _dict - def __str__(self): + 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 ClassificationCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassificationCollection') -> 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): + def __ne__(self, other: 'ClassificationCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -464,7 +494,8 @@ class ClassifiedClass(): :attr str class_name: (optional) Class label. """ - def __init__(self, *, confidence=None, class_name=None): + def __init__(self, *, confidence: float = None, + class_name: str = None) -> None: """ Initialize a ClassifiedClass object. @@ -477,7 +508,7 @@ def __init__(self, *, confidence=None, class_name=None): self.class_name = class_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedClass': """Initialize a ClassifiedClass object from a json dictionary.""" args = {} valid_keys = ['confidence', 'class_name'] @@ -492,7 +523,12 @@ def _from_dict(cls, _dict): args['class_name'] = _dict.get('class_name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedClass 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, 'confidence') and self.confidence is not None: @@ -501,17 +537,21 @@ def _to_dict(self): _dict['class_name'] = self.class_name return _dict - def __str__(self): + 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 ClassifiedClass object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedClass') -> 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): + def __ne__(self, other: 'ClassifiedClass') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -531,14 +571,14 @@ class Classifier(): """ def __init__(self, - url, - classifier_id, + url: str, + classifier_id: str, *, - name=None, - status=None, - created=None, - status_description=None, - language=None): + name: str = None, + status: str = None, + created: datetime = None, + status_description: str = None, + language: str = None) -> None: """ Initialize a Classifier object. @@ -561,7 +601,7 @@ def __init__(self, self.language = language @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} valid_keys = [ @@ -596,7 +636,12 @@ def _from_dict(cls, _dict): args['language'] = _dict.get('language') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifier 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: @@ -617,17 +662,21 @@ def _to_dict(self): _dict['language'] = self.language return _dict - def __str__(self): + 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 Classifier object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifier') -> 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): + def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -646,21 +695,21 @@ class ClassifierList(): """ List of available classifiers. - :attr list[Classifier] classifiers: The classifiers available to the user. + :attr List[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ - def __init__(self, classifiers): + def __init__(self, classifiers: List['Classifier']) -> None: """ Initialize a ClassifierList object. - :param list[Classifier] classifiers: The classifiers available to the user. + :param List[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifierList': """Initialize a ClassifierList object from a json dictionary.""" args = {} valid_keys = ['classifiers'] @@ -679,24 +728,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierList 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, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 ClassifierList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifierList') -> 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): + def __ne__(self, other: 'ClassifierList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -708,7 +766,7 @@ class ClassifyInput(): :attr str text: The submitted phrase. The maximum length is 2048 characters. """ - def __init__(self, text): + def __init__(self, text: str) -> None: """ Initialize a ClassifyInput object. @@ -718,7 +776,7 @@ def __init__(self, text): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifyInput': """Initialize a ClassifyInput object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -734,24 +792,33 @@ def _from_dict(cls, _dict): 'Required property \'text\' not present in ClassifyInput JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifyInput 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 __str__(self): + 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 ClassifyInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifyInput') -> 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): + def __ne__(self, other: 'ClassifyInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -763,18 +830,22 @@ class CollectionItem(): :attr str text: (optional) The submitted phrase. The maximum length is 2048 characters. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten + :attr List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ - def __init__(self, *, text=None, top_class=None, classes=None): + def __init__(self, + *, + text: str = None, + top_class: str = None, + classes: List['ClassifiedClass'] = None) -> None: """ Initialize a CollectionItem object. :param str text: (optional) The submitted phrase. The maximum length is 2048 characters. :param str top_class: (optional) The class with the highest confidence. - :param list[ClassifiedClass] classes: (optional) An array of up to ten + :param List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.text = text @@ -782,7 +853,7 @@ def __init__(self, *, text=None, top_class=None, classes=None): self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionItem': """Initialize a CollectionItem object from a json dictionary.""" args = {} valid_keys = ['text', 'top_class', 'classes'] @@ -801,7 +872,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionItem 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: @@ -812,16 +888,20 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 CollectionItem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionItem') -> 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): + def __ne__(self, other: 'CollectionItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 5e923b18d..d02f9bbc8 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,136 +1,544 @@ -# coding: utf-8 -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses -import ibm_watson -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -def test_success(): - authenticator = BasicAuthenticator('username', 'password') - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) - - list_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' - list_response = '{"classifiers": [{"url": "https://gateway.watsonplatform.net/natural-language-classifier-' \ - 'experimental/api/v1/classifiers/497EF2-nlc-00", "classifier_id": "497EF2-nlc-00"}]}' - responses.add(responses.GET, list_url, - body=list_response, status=200, - content_type='application/json') - - natural_language_classifier.list_classifiers() - - assert responses.calls[0].request.url == list_url - assert responses.calls[0].response.text == list_response - - status_url = ('https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' - '497EF2-nlc-00') - status_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ - 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ - 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ - '"497EF2-nlc-00"}' - - responses.add(responses.GET, status_url, - body=status_response, status=200, - content_type='application/json') - - natural_language_classifier.get_classifier('497EF2-nlc-00') - - assert responses.calls[1].request.url == status_url - assert responses.calls[1].response.text == status_response - - classify_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' \ - '497EF2-nlc-00/classify' - classify_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/' \ - 'v1", "text": "test", "classes": [{"class_name": "conditions", "confidence": ' \ - '0.6575315710901418}, {"class_name": "temperature", "confidence": 0.3424684289098582}], ' \ - '"classifier_id": "497EF2-nlc-00", "top_class": "conditions"}' - - responses.add(responses.POST, classify_url, - body=classify_response, status=200, - content_type='application/json') - - natural_language_classifier.classify('497EF2-nlc-00', 'test') - - assert responses.calls[2].request.url == classify_url - assert responses.calls[2].response.text == classify_response - - create_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' - create_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ - 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ - 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ - '"497EF2-nlc-00"}' - - responses.add(responses.POST, create_url, - body=create_response, status=200, - content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/weather_data_train.csv'), 'rb') as training_data: - natural_language_classifier.create_classifier( - training_metadata='{"language": "en"}', - training_data=training_data) - - assert responses.calls[3].request.url == create_url - assert responses.calls[3].response.text == create_response - - remove_url = status_url - remove_response = '{}' - - responses.add(responses.DELETE, remove_url, - body=remove_response, status=200, - content_type='application/json') - - natural_language_classifier.delete_classifier('497EF2-nlc-00') - - assert responses.calls[4].request.url == remove_url - assert responses.calls[4].response.text == remove_response - - assert len(responses.calls) == 5 - -@responses.activate -def test_classify_collection(): - authenticator = BasicAuthenticator('username', 'password') - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) - classify_collection_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/497EF2-nlc-00/classify_collection' - classify_collection_response = '{ \ - "classifier_id": "497EF2-nlc-00", \ - "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1", \ - "collection": [ \ - { \ - "text": "How hot will it be today?", \ - "top_class": "temperature", \ - "classes": [ \ - { \ - "class_name": "temperature", \ - "confidence": 0.9930558798985937 \ - }, \ - { \ - "class_name": "conditions", \ - "confidence": 0.006944120101406304 \ - } \ - ] \ - }, \ - { \ - "text": "Is it hot outside?", \ - "top_class": "temperature", \ - "classes": [ \ - { \ - "class_name": "temperature", \ - "confidence": 1 \ - }, \ - { \ - "class_name": "conditions", \ - "confidence": 0 \ - } \ - ] \ - } \ - ] \ - }' - responses.add(responses.POST, classify_collection_url, - body=classify_collection_response, status=200, - content_type='application/json') - - classifier_id = '497EF2-nlc-00' - collection = ['{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}'] - natural_language_classifier.classify_collection(classifier_id, collection) - - assert responses.calls[0].request.url == classify_collection_url - assert responses.calls[0].response.text == classify_collection_response +import tempfile +import ibm_watson.natural_language_classifier_v1 +from ibm_watson.natural_language_classifier_v1 import * + +base_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + +############################################################################## +# Start of Service: ClassifyText +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for classify +#----------------------------------------------------------------------------- +class TestClassify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_response(self): + body = self.construct_full_body() + response = fake_response_Classification_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classification_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_empty(self): + check_empty_required_params(self, fake_response_Classification_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}/classify'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "text": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "text": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for classify_collection +#----------------------------------------------------------------------------- +class TestClassifyCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_collection_response(self): + body = self.construct_full_body() + response = fake_response_ClassificationCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassificationCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_collection_empty(self): + check_empty_required_params( + self, fake_response_ClassificationCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}/classify_collection'.format( + body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.classify_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "collection": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "collection": [], + }) + return body + + +# endregion +############################################################################## +# End of Service: ClassifyText +############################################################################## + +############################################################################## +# Start of Service: ManageClassifiers +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_classifier +#----------------------------------------------------------------------------- +class TestCreateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['training_metadata'] = tempfile.NamedTemporaryFile() + body['training_data'] = tempfile.NamedTemporaryFile() + return body + + def construct_required_body(self): + body = dict() + body['training_metadata'] = tempfile.NamedTemporaryFile() + body['training_data'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_classifiers +#----------------------------------------------------------------------------- +class TestListClassifiers(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_response(self): + body = self.construct_full_body() + response = fake_response_ClassifierList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifierList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_classifiers(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_classifier +#----------------------------------------------------------------------------- +class TestGetClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_classifier +#----------------------------------------------------------------------------- +class TestDeleteClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: ManageClassifiers +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Classification_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "text": "fake_text", "top_class": "fake_top_class", "classes": []}""" +fake_response_ClassificationCollection_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "collection": []}""" +fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" +fake_response_ClassifierList_json = """{"classifiers": []}""" +fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" From 55b0edf2937367d249c86e04415f9278b2f77d66 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:33:28 -0500 Subject: [PATCH 10/28] refactor(nlu): regenerate natural lang understanding with tests --- .../natural_language_understanding_v1.py | 1432 +++++++++++------ .../test_natural_language_understanding_v1.py | 376 +++++ 2 files changed, 1343 insertions(+), 465 deletions(-) create mode 100644 test/unit/test_natural_language_understanding_v1.py diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 89c5dc027..8fb571cee 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. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,17 +20,23 @@ ignore most advertisements and other unwanted content. You can create [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) -with Watson Knowledge Studio to detect custom entities, relations, and categories in -Natural Language Understanding. +with Watson Knowledge Studio to detect custom entities and relations in Natural Language +Understanding. """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import Dict +from typing import List ############################################################################## # Service @@ -40,13 +46,15 @@ class NaturalLanguageUnderstandingV1(BaseService): """The Natural Language Understanding V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_NAME = 'natural-language-understanding' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Natural Language Understanding service. @@ -65,43 +73,32 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('natural_language_understanding') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'natural_language_understanding') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Analyze ######################### def analyze(self, - features, + features: 'Features', *, - text=None, - html=None, - url=None, - clean=None, - xpath=None, - fallback_to_raw=None, - return_analyzed_text=None, - language=None, - limit_text_characters=None, - **kwargs): + 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': """ Analyze text. @@ -116,6 +113,9 @@ def analyze(self, - Semantic roles - Sentiment - Syntax (Experimental). + If a language for the input text is not specified with the `language` parameter, + the service [automatically detects the + language](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-detectable-languages). :param Features features: Specific features to analyze the document for. :param str text: (optional) The plain text to analyze. One of the `text`, @@ -157,8 +157,9 @@ def analyze(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - 'analyze') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='analyze') headers.update(sdk_headers) params = {'version': self.version} @@ -181,8 +182,8 @@ def analyze(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -190,7 +191,7 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs): + def list_models(self, **kwargs) -> 'DetailedResponse': """ List models. @@ -206,8 +207,9 @@ def list_models(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - '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 = {'version': self.version} @@ -216,12 +218,12 @@ def list_models(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_model(self, model_id, **kwargs): + def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Delete model. @@ -239,8 +241,9 @@ def delete_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - '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 = {'version': self.version} @@ -249,8 +252,8 @@ def delete_model(self, model_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -269,21 +272,21 @@ class AnalysisResults(): :attr str retrieved_url: (optional) URL of the webpage that was analyzed. :attr AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr list[ConceptsResult] concepts: (optional) The general concepts referenced + :attr 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 + :attr List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :attr list[KeywordsResult] keywords: (optional) The keywords from the analyzed + :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr list[CategoriesResult] categories: (optional) The categories that the + :attr List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. :attr AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. - :attr list[RelationsResult] relations: (optional) The relationships between + :attr List[RelationsResult] relations: (optional) The relationships between entities in the content. - :attr list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into + :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 @@ -292,20 +295,20 @@ class AnalysisResults(): def __init__(self, *, - language=None, - analyzed_text=None, - retrieved_url=None, - usage=None, - concepts=None, - entities=None, - keywords=None, - categories=None, - emotion=None, - metadata=None, - relations=None, - semantic_roles=None, - sentiment=None, - syntax=None): + 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, + emotion: 'EmotionResult' = None, + metadata: 'AnalysisResultsMetadata' = None, + relations: List['RelationsResult'] = None, + semantic_roles: List['SemanticRolesResult'] = None, + sentiment: 'SentimentResult' = None, + syntax: 'SyntaxResult' = None) -> None: """ Initialize a AnalysisResults object. @@ -314,21 +317,21 @@ def __init__(self, :param str retrieved_url: (optional) URL of the webpage that was analyzed. :param AnalysisResultsUsage usage: (optional) API usage information for the request. - :param list[ConceptsResult] concepts: (optional) The general concepts + :param List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :param list[EntitiesResult] entities: (optional) The entities detected in + :param List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :param list[KeywordsResult] keywords: (optional) The keywords from the + :param List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :param list[CategoriesResult] categories: (optional) The categories that + :param List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. :param AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. - :param list[RelationsResult] relations: (optional) The relationships + :param List[RelationsResult] relations: (optional) The relationships between entities in the content. - :param list[SemanticRolesResult] semantic_roles: (optional) Sentences + :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 @@ -350,7 +353,7 @@ def __init__(self, self.syntax = syntax @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} valid_keys = [ @@ -409,7 +412,12 @@ def _from_dict(cls, _dict): args['syntax'] = SyntaxResult._from_dict(_dict.get('syntax')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResults 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, 'language') and self.language is not None: @@ -444,17 +452,21 @@ def _to_dict(self): _dict['syntax'] = self.syntax._to_dict() return _dict - def __str__(self): + 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 AnalysisResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResults') -> 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): + def __ne__(self, other: 'AnalysisResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -463,30 +475,30 @@ class AnalysisResultsMetadata(): """ Webpage metadata, such as the author and the title of the page. - :attr list[Author] authors: (optional) The authors of the document. + :attr List[Author] authors: (optional) The authors of the document. :attr 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. + :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ def __init__(self, *, - authors=None, - publication_date=None, - title=None, - image=None, - feeds=None): + authors: List['Author'] = None, + publication_date: str = None, + title: str = None, + image: str = None, + feeds: List['Feed'] = None) -> None: """ Initialize a AnalysisResultsMetadata object. - :param list[Author] authors: (optional) The authors of the document. + :param List[Author] authors: (optional) The authors of the document. :param str publication_date: (optional) The publication date in the format ISO 8601. :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. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ self.authors = authors self.publication_date = publication_date @@ -495,7 +507,7 @@ def __init__(self, self.feeds = feeds @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResultsMetadata': """Initialize a AnalysisResultsMetadata object from a json dictionary.""" args = {} valid_keys = ['authors', 'publication_date', 'title', 'image', 'feeds'] @@ -518,7 +530,12 @@ def _from_dict(cls, _dict): args['feeds'] = [Feed._from_dict(x) for x in (_dict.get('feeds'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResultsMetadata 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, 'authors') and self.authors is not None: @@ -534,17 +551,21 @@ def _to_dict(self): _dict['feeds'] = [x._to_dict() for x in self.feeds] return _dict - def __str__(self): + 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 AnalysisResultsMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResultsMetadata') -> 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): + def __ne__(self, other: 'AnalysisResultsMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -558,7 +579,11 @@ class AnalysisResultsUsage(): :attr int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, *, features=None, text_characters=None, text_units=None): + def __init__(self, + *, + features: int = None, + text_characters: int = None, + text_units: int = None) -> None: """ Initialize a AnalysisResultsUsage object. @@ -572,7 +597,7 @@ def __init__(self, *, features=None, text_characters=None, text_units=None): self.text_units = text_units @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} valid_keys = ['features', 'text_characters', 'text_units'] @@ -589,7 +614,12 @@ def _from_dict(cls, _dict): args['text_units'] = _dict.get('text_units') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResultsUsage 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, 'features') and self.features is not None: @@ -601,17 +631,21 @@ def _to_dict(self): _dict['text_units'] = self.text_units return _dict - def __str__(self): + 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 AnalysisResultsUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResultsUsage') -> 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): + def __ne__(self, other: 'AnalysisResultsUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -623,7 +657,7 @@ class Author(): :attr str name: (optional) Name of the author. """ - def __init__(self, *, name=None): + def __init__(self, *, name: str = None) -> None: """ Initialize a Author object. @@ -632,7 +666,7 @@ def __init__(self, *, name=None): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} valid_keys = ['name'] @@ -645,24 +679,33 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Author 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 return _dict - def __str__(self): + 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 Author object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Author') -> 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): + def __ne__(self, other: 'Author') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -676,12 +719,9 @@ class CategoriesOptions(): :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) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard categories model. """ - def __init__(self, *, explanation=None, limit=None, model=None): + def __init__(self, *, explanation: bool = None, limit: int = None) -> None: """ Initialize a CategoriesOptions object. @@ -689,19 +729,15 @@ def __init__(self, *, explanation=None, limit=None, model=None): 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) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard categories model. """ self.explanation = explanation self.limit = limit - self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - valid_keys = ['explanation', 'limit', 'model'] + valid_keys = ['explanation', 'limit'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -711,32 +747,37 @@ def _from_dict(cls, _dict): args['explanation'] = _dict.get('explanation') if 'limit' in _dict: args['limit'] = _dict.get('limit') - if 'model' in _dict: - args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesOptions 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, 'explanation') and self.explanation is not None: _dict['explanation'] = self.explanation if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model return _dict - def __str__(self): + 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 CategoriesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesOptions') -> 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): + def __ne__(self, other: 'CategoriesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -749,7 +790,7 @@ class CategoriesRelevantText(): categorization. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a CategoriesRelevantText object. @@ -759,7 +800,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -772,24 +813,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesRelevantText 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 __str__(self): + 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 CategoriesRelevantText object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesRelevantText') -> 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): + def __ne__(self, other: 'CategoriesRelevantText') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -808,7 +858,11 @@ class CategoriesResult(): to explain what contributed to the categories result. """ - def __init__(self, *, label=None, score=None, explanation=None): + def __init__(self, + *, + label: str = None, + score: float = None, + explanation: 'CategoriesResultExplanation' = None) -> None: """ Initialize a CategoriesResult object. @@ -827,7 +881,7 @@ def __init__(self, *, label=None, score=None, explanation=None): self.explanation = explanation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} valid_keys = ['label', 'score', 'explanation'] @@ -845,7 +899,12 @@ def _from_dict(cls, _dict): _dict.get('explanation')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesResult 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, 'label') and self.label is not None: @@ -856,17 +915,21 @@ def _to_dict(self): _dict['explanation'] = self.explanation._to_dict() return _dict - def __str__(self): + 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 CategoriesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesResult') -> 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): + def __ne__(self, other: 'CategoriesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -875,17 +938,18 @@ class CategoriesResultExplanation(): """ Information that helps to explain what contributed to the categories result. - :attr list[CategoriesRelevantText] relevant_text: (optional) An array of + :attr 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=None): + def __init__(self, *, + relevant_text: List['CategoriesRelevantText'] = None) -> None: """ Initialize a CategoriesResultExplanation object. - :param 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. @@ -893,7 +957,7 @@ def __init__(self, *, relevant_text=None): self.relevant_text = relevant_text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} valid_keys = ['relevant_text'] @@ -909,24 +973,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesResultExplanation 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, 'relevant_text') and self.relevant_text is not None: _dict['relevant_text'] = [x._to_dict() for x in self.relevant_text] return _dict - def __str__(self): + 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 CategoriesResultExplanation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesResultExplanation') -> 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): + def __ne__(self, other: 'CategoriesResultExplanation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -942,7 +1015,7 @@ class ConceptsOptions(): :attr int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, *, limit=None): + def __init__(self, *, limit: int = None) -> None: """ Initialize a ConceptsOptions object. @@ -951,7 +1024,7 @@ def __init__(self, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} valid_keys = ['limit'] @@ -964,24 +1037,33 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConceptsOptions 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, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict - def __str__(self): + 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 ConceptsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConceptsOptions') -> 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): + def __ne__(self, other: 'ConceptsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -997,7 +1079,11 @@ class ConceptsResult(): resource. """ - def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): + def __init__(self, + *, + text: str = None, + relevance: float = None, + dbpedia_resource: str = None) -> None: """ Initialize a ConceptsResult object. @@ -1012,7 +1098,7 @@ def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): self.dbpedia_resource = dbpedia_resource @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} valid_keys = ['text', 'relevance', 'dbpedia_resource'] @@ -1029,7 +1115,12 @@ def _from_dict(cls, _dict): args['dbpedia_resource'] = _dict.get('dbpedia_resource') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConceptsResult 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: @@ -1041,17 +1132,21 @@ def _to_dict(self): _dict['dbpedia_resource'] = self.dbpedia_resource return _dict - def __str__(self): + 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 ConceptsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConceptsResult') -> 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): + def __ne__(self, other: 'ConceptsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1063,7 +1158,7 @@ class DeleteModelResults(): :attr str deleted: (optional) model_id of the deleted model. """ - def __init__(self, *, deleted=None): + def __init__(self, *, deleted: str = None) -> None: """ Initialize a DeleteModelResults object. @@ -1072,7 +1167,7 @@ def __init__(self, *, deleted=None): self.deleted = deleted @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} valid_keys = ['deleted'] @@ -1085,24 +1180,33 @@ def _from_dict(cls, _dict): args['deleted'] = _dict.get('deleted') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteModelResults 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, 'deleted') and self.deleted is not None: _dict['deleted'] = self.deleted return _dict - def __str__(self): + 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 DeleteModelResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteModelResults') -> 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): + def __ne__(self, other: 'DeleteModelResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1114,24 +1218,28 @@ class DisambiguationResult(): :attr str name: (optional) Common entity name. :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :attr list[str] subtype: (optional) Entity subtype information. + :attr List[str] subtype: (optional) Entity subtype information. """ - def __init__(self, *, name=None, dbpedia_resource=None, subtype=None): + def __init__(self, + *, + name: str = None, + dbpedia_resource: str = None, + subtype: List[str] = None) -> None: """ Initialize a DisambiguationResult object. :param str name: (optional) Common entity name. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :param list[str] subtype: (optional) Entity subtype information. + :param List[str] subtype: (optional) Entity subtype information. """ self.name = name self.dbpedia_resource = dbpedia_resource self.subtype = subtype @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} valid_keys = ['name', 'dbpedia_resource', 'subtype'] @@ -1148,7 +1256,12 @@ def _from_dict(cls, _dict): args['subtype'] = _dict.get('subtype') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DisambiguationResult 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: @@ -1160,17 +1273,21 @@ def _to_dict(self): _dict['subtype'] = self.subtype return _dict - def __str__(self): + 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 DisambiguationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DisambiguationResult') -> 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): + def __ne__(self, other: 'DisambiguationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1183,7 +1300,7 @@ class DocumentEmotionResults(): whole. """ - def __init__(self, *, emotion=None): + def __init__(self, *, emotion: 'EmotionScores' = None) -> None: """ Initialize a DocumentEmotionResults object. @@ -1193,7 +1310,7 @@ def __init__(self, *, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} valid_keys = ['emotion'] @@ -1206,24 +1323,33 @@ def _from_dict(cls, _dict): args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentEmotionResults 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, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() return _dict - def __str__(self): + 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 DocumentEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentEmotionResults') -> 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): + def __ne__(self, other: 'DocumentEmotionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1238,7 +1364,7 @@ class DocumentSentimentResults(): (positive). """ - def __init__(self, *, label=None, score=None): + def __init__(self, *, label: str = None, score: float = None) -> None: """ Initialize a DocumentSentimentResults object. @@ -1251,7 +1377,7 @@ def __init__(self, *, label=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} valid_keys = ['label', 'score'] @@ -1266,7 +1392,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentSentimentResults 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, 'label') and self.label is not None: @@ -1275,17 +1406,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 DocumentSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentSentimentResults') -> 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): + def __ne__(self, other: 'DocumentSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1300,24 +1435,25 @@ class EmotionOptions(): :attr 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 + :attr List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a EmotionOptions object. :param bool document: (optional) Set this to `false` to hide document-level emotion results. - :param list[str] targets: (optional) Emotion results will be returned for + :param List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -1332,7 +1468,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionOptions 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, 'document') and self.document is not None: @@ -1341,17 +1482,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 EmotionOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionOptions') -> 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): + def __ne__(self, other: 'EmotionOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1364,24 +1509,27 @@ class EmotionResult(): :attr DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :attr list[TargetedEmotionResults] targets: (optional) Emotion results for + :attr List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, + *, + document: 'DocumentEmotionResults' = None, + targets: List['TargetedEmotionResults'] = None) -> None: """ Initialize a EmotionResult object. :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :param list[TargetedEmotionResults] targets: (optional) Emotion results for + :param List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -1400,7 +1548,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionResult 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, 'document') and self.document is not None: @@ -1409,17 +1562,21 @@ def _to_dict(self): _dict['targets'] = [x._to_dict() for x in self.targets] return _dict - def __str__(self): + 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 EmotionResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionResult') -> 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): + def __ne__(self, other: 'EmotionResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1442,11 +1599,11 @@ class EmotionScores(): def __init__(self, *, - anger=None, - disgust=None, - fear=None, - joy=None, - sadness=None): + anger: float = None, + disgust: float = None, + fear: float = None, + joy: float = None, + sadness: float = None) -> None: """ Initialize a EmotionScores object. @@ -1468,7 +1625,7 @@ def __init__(self, self.sadness = sadness @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} valid_keys = ['anger', 'disgust', 'fear', 'joy', 'sadness'] @@ -1489,7 +1646,12 @@ def _from_dict(cls, _dict): args['sadness'] = _dict.get('sadness') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionScores 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, 'anger') and self.anger is not None: @@ -1504,17 +1666,21 @@ def _to_dict(self): _dict['sadness'] = self.sadness return _dict - def __str__(self): + 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 EmotionScores object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionScores') -> 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): + def __ne__(self, other: 'EmotionScores') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1542,11 +1708,11 @@ class EntitiesOptions(): def __init__(self, *, - limit=None, - mentions=None, - model=None, - sentiment=None, - emotion=None): + limit: int = None, + mentions: bool = None, + model: str = None, + sentiment: bool = None, + emotion: bool = None) -> None: """ Initialize a EntitiesOptions object. @@ -1568,7 +1734,7 @@ def __init__(self, self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'mentions', 'model', 'sentiment', 'emotion'] @@ -1589,7 +1755,12 @@ def _from_dict(cls, _dict): args['emotion'] = _dict.get('emotion') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntitiesOptions 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, 'limit') and self.limit is not None: @@ -1604,17 +1775,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion return _dict - def __str__(self): + 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 EntitiesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntitiesOptions') -> 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): + def __ne__(self, other: 'EntitiesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1632,7 +1807,7 @@ class EntitiesResult(): 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 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. @@ -1644,15 +1819,15 @@ class EntitiesResult(): def __init__(self, *, - type=None, - text=None, - relevance=None, - confidence=None, - mentions=None, - count=None, - emotion=None, - sentiment=None, - disambiguation=None): + 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: """ Initialize a EntitiesResult object. @@ -1664,7 +1839,7 @@ def __init__(self, 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. - :param list[EntityMention] mentions: (optional) Entity mentions and + :param List[EntityMention] mentions: (optional) Entity mentions and locations. :param int count: (optional) How many times the entity was mentioned in the text. @@ -1686,7 +1861,7 @@ def __init__(self, self.disambiguation = disambiguation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} valid_keys = [ @@ -1722,7 +1897,12 @@ def _from_dict(cls, _dict): _dict.get('disambiguation')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntitiesResult 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, 'type') and self.type is not None: @@ -1745,17 +1925,21 @@ def _to_dict(self): _dict['disambiguation'] = self.disambiguation._to_dict() return _dict - def __str__(self): + 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 EntitiesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntitiesResult') -> 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): + def __ne__(self, other: 'EntitiesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1765,7 +1949,7 @@ class EntityMention(): EntityMention. :attr str text: (optional) Entity mention text. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr 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 0 to 1. Higher values indicate higher confidence. In standard entities requests, @@ -1773,12 +1957,16 @@ class EntityMention(): custom models return the confidence score. """ - def __init__(self, *, text=None, location=None, confidence=None): + def __init__(self, + *, + text: str = None, + location: List[int] = None, + confidence: float = None) -> None: """ Initialize a EntityMention object. :param str text: (optional) Entity mention text. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities @@ -1790,7 +1978,7 @@ def __init__(self, *, text=None, location=None, confidence=None): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'confidence'] @@ -1807,7 +1995,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMention 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: @@ -1818,17 +2011,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 EntityMention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMention') -> 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): + def __ne__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1841,7 +2038,7 @@ class FeatureSentimentResults(): (positive). """ - def __init__(self, *, score=None): + def __init__(self, *, score: float = None) -> None: """ Initialize a FeatureSentimentResults object. @@ -1851,7 +2048,7 @@ def __init__(self, *, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} valid_keys = ['score'] @@ -1864,24 +2061,33 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeatureSentimentResults 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, 'score') and self.score is not None: _dict['score'] = self.score return _dict - def __str__(self): + 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 FeatureSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeatureSentimentResults') -> 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): + def __ne__(self, other: 'FeatureSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1940,16 +2146,16 @@ class Features(): def __init__(self, *, - concepts=None, - emotion=None, - entities=None, - keywords=None, - metadata=None, - relations=None, - semantic_roles=None, - sentiment=None, - categories=None, - syntax=None): + concepts: 'ConceptsOptions' = None, + emotion: 'EmotionOptions' = None, + entities: 'EntitiesOptions' = None, + keywords: 'KeywordsOptions' = None, + metadata: 'MetadataOptions' = None, + relations: 'RelationsOptions' = None, + semantic_roles: 'SemanticRolesOptions' = None, + sentiment: 'SentimentOptions' = None, + categories: 'CategoriesOptions' = None, + syntax: 'SyntaxOptions' = None) -> None: """ Initialize a Features object. @@ -2013,7 +2219,7 @@ def __init__(self, self.syntax = syntax @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} valid_keys = [ @@ -2051,7 +2257,12 @@ def _from_dict(cls, _dict): args['syntax'] = SyntaxOptions._from_dict(_dict.get('syntax')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Features 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, 'concepts') and self.concepts is not None: @@ -2076,17 +2287,21 @@ def _to_dict(self): _dict['syntax'] = self.syntax._to_dict() return _dict - def __str__(self): + 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 Features object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Features') -> 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): + def __ne__(self, other: 'Features') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2098,7 +2313,7 @@ class Feed(): :attr str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, *, link=None): + def __init__(self, *, link: str = None) -> None: """ Initialize a Feed object. @@ -2107,7 +2322,7 @@ def __init__(self, *, link=None): self.link = link @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} valid_keys = ['link'] @@ -2120,24 +2335,33 @@ def _from_dict(cls, _dict): args['link'] = _dict.get('link') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Feed 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, 'link') and self.link is not None: _dict['link'] = self.link return _dict - def __str__(self): + 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 Feed object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Feed') -> 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): + def __ne__(self, other: 'Feed') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2155,7 +2379,11 @@ class KeywordsOptions(): detected keywords. """ - def __init__(self, *, limit=None, sentiment=None, emotion=None): + def __init__(self, + *, + limit: int = None, + sentiment: bool = None, + emotion: bool = None) -> None: """ Initialize a KeywordsOptions object. @@ -2170,7 +2398,7 @@ def __init__(self, *, limit=None, sentiment=None, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'sentiment', 'emotion'] @@ -2187,7 +2415,12 @@ def _from_dict(cls, _dict): args['emotion'] = _dict.get('emotion') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordsOptions 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, 'limit') and self.limit is not None: @@ -2198,17 +2431,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion return _dict - def __str__(self): + 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 KeywordsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordsOptions') -> 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): + def __ne__(self, other: 'KeywordsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2230,11 +2467,11 @@ class KeywordsResult(): def __init__(self, *, - count=None, - relevance=None, - text=None, - emotion=None, - sentiment=None): + count: int = None, + relevance: float = None, + text: str = None, + emotion: 'EmotionScores' = None, + sentiment: 'FeatureSentimentResults' = None) -> None: """ Initialize a KeywordsResult object. @@ -2255,7 +2492,7 @@ def __init__(self, self.sentiment = sentiment @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} valid_keys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] @@ -2277,7 +2514,12 @@ def _from_dict(cls, _dict): _dict.get('sentiment')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordsResult 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, 'count') and self.count is not None: @@ -2292,17 +2534,21 @@ def _to_dict(self): _dict['sentiment'] = self.sentiment._to_dict() return _dict - def __str__(self): + 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 KeywordsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordsResult') -> 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): + def __ne__(self, other: 'KeywordsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2311,19 +2557,19 @@ class ListModelsResults(): """ Custom models that are available for entities and relations. - :attr list[Model] models: (optional) An array of available models. + :attr List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models=None): + def __init__(self, *, models: List['Model'] = None) -> None: """ Initialize a ListModelsResults object. - :param list[Model] models: (optional) An array of available models. + :param List[Model] models: (optional) An array of available models. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -2338,24 +2584,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListModelsResults 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 ListModelsResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListModelsResults') -> 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): + def __ne__(self, other: 'ListModelsResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2367,34 +2622,43 @@ class MetadataOptions(): """ - def __init__(self): + def __init__(self) -> None: """ Initialize a MetadataOptions object. """ @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetadataOptions': """Initialize a MetadataOptions object from a json dictionary.""" args = {} return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetadataOptions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} return _dict - def __str__(self): + 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 MetadataOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetadataOptions') -> 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): + def __ne__(self, other: 'MetadataOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2421,14 +2685,14 @@ class Model(): def __init__(self, *, - status=None, - model_id=None, - language=None, - description=None, - workspace_id=None, - version=None, - version_description=None, - created=None): + status: str = None, + model_id: str = None, + language: str = None, + description: str = None, + workspace_id: str = None, + version: str = None, + version_description: str = None, + created: datetime = None) -> None: """ Initialize a Model object. @@ -2457,7 +2721,7 @@ def __init__(self, self.created = created @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} valid_keys = [ @@ -2487,7 +2751,12 @@ def _from_dict(cls, _dict): args['created'] = string_to_datetime(_dict.get('created')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Model 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, 'status') and self.status is not None: @@ -2510,17 +2779,21 @@ def _to_dict(self): _dict['created'] = datetime_to_string(self.created) return _dict - def __str__(self): + 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 Model object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Model') -> 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): + def __ne__(self, other: 'Model') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2529,19 +2802,23 @@ class RelationArgument(): """ RelationArgument. - :attr list[RelationEntity] entities: (optional) An array of extracted entities. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[RelationEntity] entities: (optional) An array of extracted entities. + :attr 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. """ - def __init__(self, *, entities=None, location=None, text=None): + def __init__(self, + *, + entities: List['RelationEntity'] = None, + location: List[int] = None, + text: str = None) -> None: """ Initialize a RelationArgument object. - :param list[RelationEntity] entities: (optional) An array of extracted + :param List[RelationEntity] entities: (optional) An array of extracted entities. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :param str text: (optional) Text that corresponds to the argument. """ @@ -2550,7 +2827,7 @@ def __init__(self, *, entities=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} valid_keys = ['entities', 'location', 'text'] @@ -2569,7 +2846,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationArgument 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, 'entities') and self.entities is not None: @@ -2580,17 +2862,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 RelationArgument object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationArgument') -> 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): + def __ne__(self, other: 'RelationArgument') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2603,7 +2889,7 @@ class RelationEntity(): :attr str type: (optional) Entity type. """ - def __init__(self, *, text=None, type=None): + def __init__(self, *, text: str = None, type: str = None) -> None: """ Initialize a RelationEntity object. @@ -2614,7 +2900,7 @@ def __init__(self, *, text=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} valid_keys = ['text', 'type'] @@ -2629,7 +2915,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationEntity 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: @@ -2638,17 +2929,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 RelationEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationEntity') -> 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): + def __ne__(self, other: 'RelationEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2667,7 +2962,7 @@ class RelationsOptions(): ID to override the default model. """ - def __init__(self, *, model=None): + def __init__(self, *, model: str = None) -> None: """ Initialize a RelationsOptions object. @@ -2678,7 +2973,7 @@ def __init__(self, *, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} valid_keys = ['model'] @@ -2691,24 +2986,33 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationsOptions 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, 'model') and self.model is not None: _dict['model'] = self.model return _dict - def __str__(self): + 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 RelationsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationsOptions') -> 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): + def __ne__(self, other: 'RelationsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2721,11 +3025,16 @@ class RelationsResult(): 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 + :attr List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ - def __init__(self, *, score=None, sentence=None, type=None, arguments=None): + def __init__(self, + *, + score: float = None, + sentence: str = None, + type: str = None, + arguments: List['RelationArgument'] = None) -> None: """ Initialize a RelationsResult object. @@ -2733,7 +3042,7 @@ def __init__(self, *, score=None, sentence=None, type=None, arguments=None): values indicate greater confidence. :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 + :param List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ self.score = score @@ -2742,7 +3051,7 @@ def __init__(self, *, score=None, sentence=None, type=None, arguments=None): self.arguments = arguments @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} valid_keys = ['score', 'sentence', 'type', 'arguments'] @@ -2763,7 +3072,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationsResult 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, 'score') and self.score is not None: @@ -2776,17 +3090,21 @@ def _to_dict(self): _dict['arguments'] = [x._to_dict() for x in self.arguments] return _dict - def __str__(self): + 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 RelationsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationsResult') -> 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): + def __ne__(self, other: 'RelationsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2799,7 +3117,7 @@ class SemanticRolesEntity(): :attr str text: (optional) The entity text. """ - def __init__(self, *, type=None, text=None): + def __init__(self, *, type: str = None, text: str = None) -> None: """ Initialize a SemanticRolesEntity object. @@ -2810,7 +3128,7 @@ def __init__(self, *, type=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} valid_keys = ['type', 'text'] @@ -2825,7 +3143,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesEntity 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, 'type') and self.type is not None: @@ -2834,17 +3157,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 SemanticRolesEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesEntity') -> 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): + def __ne__(self, other: 'SemanticRolesEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2856,7 +3183,7 @@ class SemanticRolesKeyword(): :attr str text: (optional) The keyword text. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a SemanticRolesKeyword object. @@ -2865,7 +3192,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -2878,24 +3205,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesKeyword 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 __str__(self): + 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 SemanticRolesKeyword object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesKeyword') -> 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): + def __ne__(self, other: 'SemanticRolesKeyword') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2912,7 +3248,11 @@ class SemanticRolesOptions(): for subjects and objects. """ - def __init__(self, *, limit=None, keywords=None, entities=None): + def __init__(self, + *, + limit: int = None, + keywords: bool = None, + entities: bool = None) -> None: """ Initialize a SemanticRolesOptions object. @@ -2928,7 +3268,7 @@ def __init__(self, *, limit=None, keywords=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'keywords', 'entities'] @@ -2945,7 +3285,12 @@ def _from_dict(cls, _dict): args['entities'] = _dict.get('entities') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesOptions 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, 'limit') and self.limit is not None: @@ -2956,17 +3301,21 @@ def _to_dict(self): _dict['entities'] = self.entities return _dict - def __str__(self): + 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 SemanticRolesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesOptions') -> 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): + def __ne__(self, other: 'SemanticRolesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2985,8 +3334,12 @@ class SemanticRolesResult(): sentence. """ - def __init__(self, *, sentence=None, subject=None, action=None, - object=None): + def __init__(self, + *, + sentence: str = None, + subject: 'SemanticRolesResultSubject' = None, + action: 'SemanticRolesResultAction' = None, + object: 'SemanticRolesResultObject' = None) -> None: """ Initialize a SemanticRolesResult object. @@ -3005,7 +3358,7 @@ def __init__(self, *, sentence=None, subject=None, action=None, self.object = object @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} valid_keys = ['sentence', 'subject', 'action', 'object'] @@ -3027,7 +3380,12 @@ def _from_dict(cls, _dict): _dict.get('object')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResult 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, 'sentence') and self.sentence is not None: @@ -3040,17 +3398,21 @@ def _to_dict(self): _dict['object'] = self.object._to_dict() return _dict - def __str__(self): + 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 SemanticRolesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResult') -> 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): + def __ne__(self, other: 'SemanticRolesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3064,7 +3426,11 @@ class SemanticRolesResultAction(): :attr SemanticRolesVerb verb: (optional) """ - def __init__(self, *, text=None, normalized=None, verb=None): + def __init__(self, + *, + text: str = None, + normalized: str = None, + verb: 'SemanticRolesVerb' = None) -> None: """ Initialize a SemanticRolesResultAction object. @@ -3077,7 +3443,7 @@ def __init__(self, *, text=None, normalized=None, verb=None): self.verb = verb @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} valid_keys = ['text', 'normalized', 'verb'] @@ -3094,7 +3460,12 @@ def _from_dict(cls, _dict): args['verb'] = SemanticRolesVerb._from_dict(_dict.get('verb')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultAction 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: @@ -3105,17 +3476,21 @@ def _to_dict(self): _dict['verb'] = self.verb._to_dict() return _dict - def __str__(self): + 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 SemanticRolesResultAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultAction') -> 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): + def __ne__(self, other: 'SemanticRolesResultAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3125,23 +3500,26 @@ class SemanticRolesResultObject(): The extracted object from the sentence. :attr str text: (optional) Object text. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, *, text=None, keywords=None): + def __init__(self, + *, + text: str = None, + keywords: List['SemanticRolesKeyword'] = None) -> None: """ Initialize a SemanticRolesResultObject object. :param str text: (optional) Object text. - :param list[SemanticRolesKeyword] keywords: (optional) An array of + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text self.keywords = keywords @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} valid_keys = ['text', 'keywords'] @@ -3159,7 +3537,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultObject 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: @@ -3168,17 +3551,21 @@ def _to_dict(self): _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict - def __str__(self): + 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 SemanticRolesResultObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultObject') -> 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): + def __ne__(self, other: 'SemanticRolesResultObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3188,20 +3575,24 @@ 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 + :attr List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, *, text=None, entities=None, keywords=None): + def __init__(self, + *, + text: str = None, + entities: List['SemanticRolesEntity'] = None, + keywords: List['SemanticRolesKeyword'] = None) -> None: """ Initialize a SemanticRolesResultSubject object. :param str text: (optional) Text that corresponds to the subject role. - :param list[SemanticRolesEntity] entities: (optional) An array of extracted + :param List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :param list[SemanticRolesKeyword] keywords: (optional) An array of + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text @@ -3209,7 +3600,7 @@ def __init__(self, *, text=None, entities=None, keywords=None): self.keywords = keywords @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} valid_keys = ['text', 'entities', 'keywords'] @@ -3232,7 +3623,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultSubject 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: @@ -3243,17 +3639,21 @@ def _to_dict(self): _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict - def __str__(self): + 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 SemanticRolesResultSubject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultSubject') -> 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): + def __ne__(self, other: 'SemanticRolesResultSubject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3266,7 +3666,7 @@ class SemanticRolesVerb(): :attr str tense: (optional) Verb tense. """ - def __init__(self, *, text=None, tense=None): + def __init__(self, *, text: str = None, tense: str = None) -> None: """ Initialize a SemanticRolesVerb object. @@ -3277,7 +3677,7 @@ def __init__(self, *, text=None, tense=None): self.tense = tense @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} valid_keys = ['text', 'tense'] @@ -3292,7 +3692,12 @@ def _from_dict(cls, _dict): args['tense'] = _dict.get('tense') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesVerb 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: @@ -3301,17 +3706,21 @@ def _to_dict(self): _dict['tense'] = self.tense return _dict - def __str__(self): + 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 SemanticRolesVerb object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesVerb') -> 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): + def __ne__(self, other: 'SemanticRolesVerb') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3321,23 +3730,23 @@ class SentenceResult(): SentenceResult. :attr str text: (optional) The sentence. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, location: List[int] = None) -> None: """ Initialize a SentenceResult object. :param str text: (optional) The sentence. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ self.text = text self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -3352,7 +3761,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentenceResult 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: @@ -3361,17 +3775,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 SentenceResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentenceResult') -> 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): + def __ne__(self, other: 'SentenceResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3386,24 +3804,25 @@ class SentimentOptions(): :attr 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 + :attr List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a SentimentOptions object. :param bool document: (optional) Set this to `false` to hide document-level sentiment results. - :param list[str] targets: (optional) Sentiment results will be returned for + :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -3418,7 +3837,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentimentOptions 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, 'document') and self.document is not None: @@ -3427,17 +3851,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 SentimentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentimentOptions') -> 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): + def __ne__(self, other: 'SentimentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3448,24 +3876,27 @@ class SentimentResult(): :attr DocumentSentimentResults document: (optional) The document level sentiment. - :attr list[TargetedSentimentResults] targets: (optional) The targeted sentiment + :attr List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, + *, + document: 'DocumentSentimentResults' = None, + targets: List['TargetedSentimentResults'] = None) -> None: """ Initialize a SentimentResult object. :param DocumentSentimentResults document: (optional) The document level sentiment. - :param list[TargetedSentimentResults] targets: (optional) The targeted + :param List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -3484,7 +3915,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentimentResult 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, 'document') and self.document is not None: @@ -3493,17 +3929,21 @@ def _to_dict(self): _dict['targets'] = [x._to_dict() for x in self.targets] return _dict - def __str__(self): + 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 SentimentResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentimentResult') -> 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): + def __ne__(self, other: 'SentimentResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3517,7 +3957,10 @@ class SyntaxOptions(): information. """ - def __init__(self, *, tokens=None, sentences=None): + def __init__(self, + *, + tokens: 'SyntaxOptionsTokens' = None, + sentences: bool = None) -> None: """ Initialize a SyntaxOptions object. @@ -3529,7 +3972,7 @@ def __init__(self, *, tokens=None, sentences=None): self.sentences = sentences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} valid_keys = ['tokens', 'sentences'] @@ -3544,7 +3987,12 @@ def _from_dict(cls, _dict): args['sentences'] = _dict.get('sentences') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxOptions 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, 'tokens') and self.tokens is not None: @@ -3553,17 +4001,21 @@ def _to_dict(self): _dict['sentences'] = self.sentences return _dict - def __str__(self): + 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 SyntaxOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxOptions') -> 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): + def __ne__(self, other: 'SyntaxOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3578,7 +4030,8 @@ class SyntaxOptionsTokens(): speech for each token. """ - def __init__(self, *, lemma=None, part_of_speech=None): + def __init__(self, *, lemma: bool = None, + part_of_speech: bool = None) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -3591,7 +4044,7 @@ def __init__(self, *, lemma=None, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} valid_keys = ['lemma', 'part_of_speech'] @@ -3606,7 +4059,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxOptionsTokens 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, 'lemma') and self.lemma is not None: @@ -3615,17 +4073,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 SyntaxOptionsTokens object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxOptionsTokens') -> 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): + def __ne__(self, other: 'SyntaxOptionsTokens') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3634,22 +4096,25 @@ class SyntaxResult(): """ Tokens and sentences returned from syntax analysis. - :attr list[TokenResult] tokens: (optional) - :attr list[SentenceResult] sentences: (optional) + :attr List[TokenResult] tokens: (optional) + :attr List[SentenceResult] sentences: (optional) """ - def __init__(self, *, tokens=None, sentences=None): + def __init__(self, + *, + tokens: List['TokenResult'] = None, + sentences: List['SentenceResult'] = None) -> None: """ Initialize a SyntaxResult object. - :param list[TokenResult] tokens: (optional) - :param list[SentenceResult] sentences: (optional) + :param List[TokenResult] tokens: (optional) + :param List[SentenceResult] sentences: (optional) """ self.tokens = tokens self.sentences = sentences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} valid_keys = ['tokens', 'sentences'] @@ -3668,7 +4133,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxResult 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, 'tokens') and self.tokens is not None: @@ -3677,17 +4147,21 @@ def _to_dict(self): _dict['sentences'] = [x._to_dict() for x in self.sentences] return _dict - def __str__(self): + 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 SyntaxResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxResult') -> 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): + def __ne__(self, other: 'SyntaxResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3700,7 +4174,8 @@ class TargetedEmotionResults(): :attr EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, *, text=None, emotion=None): + def __init__(self, *, text: str = None, + emotion: 'EmotionScores' = None) -> None: """ Initialize a TargetedEmotionResults object. @@ -3712,7 +4187,7 @@ def __init__(self, *, text=None, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} valid_keys = ['text', 'emotion'] @@ -3727,7 +4202,12 @@ def _from_dict(cls, _dict): args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TargetedEmotionResults 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: @@ -3736,17 +4216,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion._to_dict() return _dict - def __str__(self): + 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 TargetedEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TargetedEmotionResults') -> 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): + def __ne__(self, other: 'TargetedEmotionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3760,7 +4244,7 @@ class TargetedSentimentResults(): (positive). """ - def __init__(self, *, text=None, score=None): + def __init__(self, *, text: str = None, score: float = None) -> None: """ Initialize a TargetedSentimentResults object. @@ -3772,7 +4256,7 @@ def __init__(self, *, text=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} valid_keys = ['text', 'score'] @@ -3787,7 +4271,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TargetedSentimentResults 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: @@ -3796,17 +4285,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 TargetedSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TargetedSentimentResults') -> 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): + def __ne__(self, other: 'TargetedSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3819,7 +4312,7 @@ class TokenResult(): :attr str part_of_speech: (optional) The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. :attr str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. @@ -3827,10 +4320,10 @@ class TokenResult(): def __init__(self, *, - text=None, - part_of_speech=None, - location=None, - lemma=None): + text: str = None, + part_of_speech: str = None, + location: List[int] = None, + lemma: str = None) -> None: """ Initialize a TokenResult object. @@ -3838,7 +4331,7 @@ def __init__(self, :param str part_of_speech: (optional) The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. :param str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. @@ -3849,7 +4342,7 @@ def __init__(self, self.lemma = lemma @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} valid_keys = ['text', 'part_of_speech', 'location', 'lemma'] @@ -3868,7 +4361,12 @@ def _from_dict(cls, _dict): args['lemma'] = _dict.get('lemma') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenResult 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: @@ -3881,17 +4379,21 @@ def _to_dict(self): _dict['lemma'] = self.lemma return _dict - def __str__(self): + 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 TokenResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenResult') -> 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): + def __ne__(self, other: 'TokenResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py new file mode 100644 index 000000000..e567e8f07 --- /dev/null +++ b/test/unit/test_natural_language_understanding_v1.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest +import responses +import tempfile +import ibm_watson.natural_language_understanding_v1 +from ibm_watson.natural_language_understanding_v1 import * + +base_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + +############################################################################## +# Start of Service: Analyze +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for analyze +#----------------------------------------------------------------------------- +class TestAnalyze(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_response(self): + body = self.construct_full_body() + response = fake_response_AnalysisResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AnalysisResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_empty(self): + check_empty_required_params(self, fake_response_AnalysisResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/analyze' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.analyze(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "features": + Features._from_dict( + json.loads( + """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" + )), + "text": + "string1", + "html": + "string1", + "url": + "string1", + "clean": + True, + "xpath": + "string1", + "fallback_to_raw": + True, + "return_analyzed_text": + True, + "language": + "string1", + "limit_text_characters": + 12345, + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "features": + Features._from_dict( + json.loads( + """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" + )), + "text": + "string1", + "html": + "string1", + "url": + "string1", + "clean": + True, + "xpath": + "string1", + "fallback_to_raw": + True, + "return_analyzed_text": + True, + "language": + "string1", + "limit_text_characters": + 12345, + }) + return body + + +# endregion +############################################################################## +# End of Service: Analyze +############################################################################## + +############################################################################## +# Start of Service: ManageModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_ListModelsResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListModelsResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_model +#----------------------------------------------------------------------------- +class TestDeleteModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_response(self): + body = self.construct_full_body() + response = fake_response_DeleteModelResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteModelResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_empty(self): + check_empty_required_params(self, fake_response_DeleteModelResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models/{0}'.format(body['model_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.delete_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: ManageModels +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_AnalysisResults_json = """{"language": "fake_language", "analyzed_text": "fake_analyzed_text", "retrieved_url": "fake_retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [], "entities": [], "keywords": [], "categories": [], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": []}, "metadata": {"authors": [], "publication_date": "fake_publication_date", "title": "fake_title", "image": "fake_image", "feeds": []}, "relations": [], "semantic_roles": [], "sentiment": {"document": {"label": "fake_label", "score": 5}, "targets": []}, "syntax": {"tokens": [], "sentences": []}}""" +fake_response_ListModelsResults_json = """{"models": []}""" +fake_response_DeleteModelResults_json = """{"deleted": "fake_deleted"}""" From 68dfef715ec6435ba2c895276ddfb8595b4a8bea Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:34:42 -0500 Subject: [PATCH 11/28] refactor(pi): regenerate personality insights with tests --- ibm_watson/personality_insights_v3.py | 326 +++++++++++++--------- test/unit/test_personality_insights_v3.py | 298 ++++++++++++-------- 2 files changed, 382 insertions(+), 242 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 2bdd20062..2f99e5075 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -34,11 +34,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -48,13 +52,15 @@ class PersonalityInsightsV3(BaseService): """The Personality Insights V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_NAME = 'personality_insights' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Personality Insights service. @@ -73,41 +79,30 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('personality_insights') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'personality_insights') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Methods ######################### def profile(self, - content, - accept, + content: object, + accept: str, *, - content_type=None, - content_language=None, - accept_language=None, - raw_scores=None, - csv_headers=None, - consumption_preferences=None, - **kwargs): + content_type: str = None, + content_language: str = None, + accept_language: str = None, + raw_scores: bool = None, + csv_headers: bool = None, + consumption_preferences: bool = None, + **kwargs) -> 'DetailedResponse': """ Get profile. @@ -200,7 +195,9 @@ def profile(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('personality_insights', 'V3', 'profile') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='profile') headers.update(sdk_headers) params = { @@ -216,13 +213,12 @@ def profile(self, data = content url = '/v3/profile' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=(accept is None or accept == 'application/json')) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + response = self.send(request) return response @@ -305,7 +301,8 @@ class Behavior(): day. The range is 0 to 1. """ - def __init__(self, trait_id, name, category, percentage): + def __init__(self, trait_id: str, name: str, category: str, + percentage: float) -> None: """ Initialize a Behavior object. @@ -325,7 +322,7 @@ def __init__(self, trait_id, name, category, percentage): self.percentage = percentage @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Behavior': """Initialize a Behavior object from a json dictionary.""" args = {} valid_keys = ['trait_id', 'name', 'category', 'percentage'] @@ -356,7 +353,12 @@ def _from_dict(cls, _dict): 'Required property \'percentage\' not present in Behavior JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Behavior 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, 'trait_id') and self.trait_id is not None: @@ -369,17 +371,21 @@ def _to_dict(self): _dict['percentage'] = self.percentage return _dict - def __str__(self): + 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 Behavior object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Behavior') -> 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): + def __ne__(self, other: 'Behavior') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -401,7 +407,8 @@ class ConsumptionPreferences(): input text, not a normalized percentile. """ - def __init__(self, consumption_preference_id, name, score): + def __init__(self, consumption_preference_id: str, name: str, + score: float) -> None: """ Initialize a ConsumptionPreferences object. @@ -423,7 +430,7 @@ def __init__(self, consumption_preference_id, name, score): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferences': """Initialize a ConsumptionPreferences object from a json dictionary.""" args = {} valid_keys = ['consumption_preference_id', 'name', 'score'] @@ -453,7 +460,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConsumptionPreferences 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, 'consumption_preference_id' @@ -465,17 +477,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 ConsumptionPreferences object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConsumptionPreferences') -> 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): + def __ne__(self, other: 'ConsumptionPreferences') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -488,12 +504,13 @@ class ConsumptionPreferencesCategory(): identifier of the consumption preferences category to which the results pertain. IDs have the form `consumption_preferences_{category}`. :attr str name: The user-visible name of the consumption preferences category. - :attr list[ConsumptionPreferences] consumption_preferences: Detailed results + :attr List[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ - def __init__(self, consumption_preference_category_id, name, - consumption_preferences): + def __init__(self, consumption_preference_category_id: str, name: str, + consumption_preferences: List['ConsumptionPreferences'] + ) -> None: """ Initialize a ConsumptionPreferencesCategory object. @@ -502,7 +519,7 @@ def __init__(self, consumption_preference_category_id, name, pertain. IDs have the form `consumption_preferences_{category}`. :param str name: The user-visible name of the consumption preferences category. - :param list[ConsumptionPreferences] consumption_preferences: Detailed + :param List[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ @@ -511,7 +528,7 @@ def __init__(self, consumption_preference_category_id, name, self.consumption_preferences = consumption_preferences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferencesCategory': """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} valid_keys = [ @@ -547,7 +564,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConsumptionPreferencesCategory 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, 'consumption_preference_category_id' @@ -563,17 +585,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ConsumptionPreferencesCategory object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConsumptionPreferencesCategory') -> 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): + def __ne__(self, other: 'ConsumptionPreferencesCategory') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -582,21 +608,21 @@ class Content(): """ The full input content that the service is to analyze. - :attr list[ContentItem] content_items: An array of `ContentItem` objects that + :attr List[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ - def __init__(self, content_items): + def __init__(self, content_items: List['ContentItem']) -> None: """ Initialize a Content object. - :param list[ContentItem] content_items: An array of `ContentItem` objects + :param List[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ self.content_items = content_items @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Content': """Initialize a Content object from a json dictionary.""" args = {} valid_keys = ['content_items', 'contentItems'] @@ -615,24 +641,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Content 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, 'content_items') and self.content_items is not None: _dict['contentItems'] = [x._to_dict() for x in self.content_items] return _dict - def __str__(self): + 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 Content object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Content') -> 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): + def __ne__(self, other: 'Content') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -673,16 +708,16 @@ class ContentItem(): """ def __init__(self, - content, + content: str, *, - id=None, - created=None, - updated=None, - contenttype=None, - language=None, - parentid=None, - reply=None, - forward=None): + id: str = None, + created: int = None, + updated: int = None, + contenttype: str = None, + language: str = None, + parentid: str = None, + reply: bool = None, + forward: bool = None) -> None: """ Initialize a ContentItem object. @@ -729,7 +764,7 @@ def __init__(self, self.forward = forward @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContentItem': """Initialize a ContentItem object from a json dictionary.""" args = {} valid_keys = [ @@ -764,7 +799,12 @@ def _from_dict(cls, _dict): args['forward'] = _dict.get('forward') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContentItem 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, 'content') and self.content is not None: @@ -787,17 +827,21 @@ def _to_dict(self): _dict['forward'] = self.forward return _dict - def __str__(self): + 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 ContentItem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContentItem') -> 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): + def __ne__(self, other: 'ContentItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -839,38 +883,39 @@ class Profile(): :attr str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. - :attr list[Trait] personality: A recursive array of `Trait` objects that + :attr List[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. - :attr list[Trait] needs: Detailed results for the Needs characteristics inferred + :attr List[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. - :attr list[Trait] values: Detailed results for the Values characteristics + :attr List[Trait] values: Detailed results for the Values characteristics inferred from the input text. - :attr list[Behavior] behavior: (optional) For JSON content that is timestamped, + :attr List[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. - :attr list[ConsumptionPreferencesCategory] consumption_preferences: (optional) + :attr List[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual preferences of that category. - :attr list[Warning] warnings: An array of warning messages that are associated + :attr List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. """ def __init__(self, - processed_language, - word_count, - personality, - needs, - values, - warnings, + processed_language: str, + word_count: int, + personality: List['Trait'], + needs: List['Trait'], + values: List['Trait'], + warnings: List['Warning'], *, - word_count_message=None, - behavior=None, - consumption_preferences=None): + word_count_message: str = None, + behavior: List['Behavior'] = None, + consumption_preferences: List[ + 'ConsumptionPreferencesCategory'] = None) -> None: """ Initialize a Profile object. @@ -878,26 +923,26 @@ def __init__(self, the input. :param int word_count: The number of words from the input that were used to produce the profile. - :param list[Trait] personality: A recursive array of `Trait` objects that + :param List[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. - :param list[Trait] needs: Detailed results for the Needs characteristics + :param List[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. - :param list[Trait] values: Detailed results for the Values characteristics + :param List[Trait] values: Detailed results for the Values characteristics inferred from the input text. - :param list[Warning] warnings: An array of warning messages that are + :param List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. :param str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. - :param list[Behavior] behavior: (optional) For JSON content that is + :param List[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. - :param list[ConsumptionPreferencesCategory] consumption_preferences: + :param List[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual @@ -914,7 +959,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Profile': """Initialize a Profile object from a json dictionary.""" args = {} valid_keys = [ @@ -977,7 +1022,12 @@ def _from_dict(cls, _dict): 'Required property \'warnings\' not present in Profile JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Profile 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( @@ -1007,17 +1057,21 @@ def _to_dict(self): _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 Profile object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Profile') -> 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): + def __ne__(self, other: 'Profile') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1065,20 +1119,20 @@ class Trait(): `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. - :attr list[Trait] children: (optional) For `personality` (Big Five) dimensions, + :attr List[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ def __init__(self, - trait_id, - name, - category, - percentile, + trait_id: str, + name: str, + category: str, + percentile: float, *, - raw_score=None, - significant=None, - children=None): + raw_score: float = None, + significant: bool = None, + children: List['Trait'] = None) -> None: """ Initialize a Trait object. @@ -1113,7 +1167,7 @@ def __init__(self, field is `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. - :param list[Trait] children: (optional) For `personality` (Big Five) + :param List[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ @@ -1126,7 +1180,7 @@ def __init__(self, self.children = children @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Trait': """Initialize a Trait object from a json dictionary.""" args = {} valid_keys = [ @@ -1168,7 +1222,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Trait 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, 'trait_id') and self.trait_id is not None: @@ -1187,17 +1246,21 @@ def _to_dict(self): _dict['children'] = [x._to_dict() for x in self.children] return _dict - def __str__(self): + 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 Trait object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Trait') -> 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): + def __ne__(self, other: 'Trait') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1233,7 +1296,7 @@ class Warning(): of the profile. """ - def __init__(self, warning_id, message): + def __init__(self, warning_id: str, message: str) -> None: """ Initialize a Warning object. @@ -1258,7 +1321,7 @@ def __init__(self, warning_id, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} valid_keys = ['warning_id', 'message'] @@ -1279,7 +1342,12 @@ def _from_dict(cls, _dict): 'Required property \'message\' not present in Warning JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Warning 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, 'warning_id') and self.warning_id is not None: @@ -1288,17 +1356,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 Warning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Warning') -> 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): + def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 269346959..9fae31cba 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,116 +1,184 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses -import ibm_watson -import os -import codecs -from ibm_watson.personality_insights_v3 import Profile -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -profile_url = 'https://gateway.watsonplatform.net/personality-insights/api/v3/profile' - -@responses.activate -def test_plain_to_json(): - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect1.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.txt'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, 'application/json', content_type='text/plain;charset=utf-8').get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) - -@responses.activate -def test_json_to_json(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, accept='application/json', - content_type='application/json', - raw_scores=True, - consumption_preferences=True).get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert 'raw_scores=true' in responses.calls[0].request.url - assert 'consumption_preferences=true' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) - -@responses.activate -def test_json_to_csv(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='text/csv') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: - personality_insights.profile( - personality_text, - 'text/csv', - content_type='application/json', - csv_headers=True, - raw_scores=True, - consumption_preferences=True) - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert 'raw_scores=true' in responses.calls[0].request.url - assert 'consumption_preferences=true' in responses.calls[0].request.url - assert 'csv_headers=true' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - - -@responses.activate -def test_plain_to_json_es(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-es.txt'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, - 'application/json', - content_type='text/plain;charset=utf-8', - content_language='es', - accept_language='es').get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) +import ibm_watson.personality_insights_v3 +from ibm_watson.personality_insights_v3 import * + +base_url = 'https://gateway.watsonplatform.net/personality-insights/api' + +############################################################################## +# Start of Service: Methods +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for profile +#----------------------------------------------------------------------------- +class TestProfile(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_profile_response(self): + body = self.construct_full_body() + response = fake_response_Profile_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_profile_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Profile_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_profile_empty(self): + check_empty_required_params(self, fake_response_Profile_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/profile' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = PersonalityInsightsV3( + authenticator=NoAuthAuthenticator(), + version='2017-10-13', + ) + service.set_service_url(base_url) + output = service.profile(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"content": {"mock": "data"}}) + body['accept'] = "string1" + body['content_type'] = "string1" + body['content_language'] = "string1" + body['accept_language'] = "string1" + body['raw_scores'] = True + body['csv_headers'] = True + body['consumption_preferences'] = True + return body + + def construct_required_body(self): + body = dict() + body.update({"content": {"mock": "data"}}) + body['accept'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Methods +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Profile_json = """{"processed_language": "fake_processed_language", "word_count": 10, "word_count_message": "fake_word_count_message", "personality": [], "needs": [], "values": [], "behavior": [], "consumption_preferences": [], "warnings": []}""" From 3960fa2821217dbeb5e941bc3bdffe0b414bf923 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:35:20 -0500 Subject: [PATCH 12/28] refactor(ta): regenerate tone analyzer --- ibm_watson/tone_analyzer_v3.py | 346 ++++++++++++++++--------- test/unit/test_tone_analyzer_v3.py | 399 ++++++++++++++++++----------- 2 files changed, 482 insertions(+), 263 deletions(-) diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index c36c9523e..42287778f 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -26,11 +26,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -40,13 +44,15 @@ class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_NAME = 'tone_analyzer' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Tone Analyzer service. @@ -65,38 +71,28 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('tone_analyzer') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('tone_analyzer') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Methods ######################### def tone(self, - tone_input, + tone_input: object, *, - content_type=None, - sentences=None, - tones=None, - content_language=None, - accept_language=None, - **kwargs): + content_type: str = None, + sentences: bool = None, + tones: List[str] = None, + content_language: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Analyze general tone. @@ -128,7 +124,7 @@ def tone(self, return an analysis of each individual sentence in addition to its analysis of the full document. If `true` (the default), the service returns results for each sentence. - :param list[str] tones: (optional) **`2017-09-21`:** Deprecated. The + :param List[str] tones: (optional) **`2017-09-21`:** Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response. **`2016-05-19`:** A comma-separated list of tones for which the service is @@ -165,7 +161,9 @@ def tone(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='tone') headers.update(sdk_headers) params = { @@ -184,17 +182,17 @@ def tone(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def tone_chat(self, - utterances, + utterances: List['Utterance'], *, - content_language=None, - accept_language=None, - **kwargs): + content_language: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Analyze customer-engagement tone. @@ -211,7 +209,7 @@ def tone_chat(self, **See also:** [Using the customer-engagement endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utco#utco). - :param list[Utterance] utterances: An array of `Utterance` objects that + :param List[Utterance] utterances: An array of `Utterance` objects that provides the input content that the service is to analyze. :param str content_language: (optional) The language of the input text for the request: English or French. Regional variants are treated as their @@ -240,7 +238,9 @@ def tone_chat(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone_chat') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='tone_chat') headers.update(sdk_headers) params = {'version': self.version} @@ -252,8 +252,8 @@ def tone_chat(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -359,12 +359,12 @@ class DocumentAnalysis(): """ The results of the analysis for the full input content. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified with the `tones` parameter @@ -375,16 +375,20 @@ class DocumentAnalysis(): 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. """ - def __init__(self, *, tones=None, tone_categories=None, warning=None): + def __init__(self, + *, + tones: List['ToneScore'] = None, + tone_categories: List['ToneCategory'] = None, + warning: str = None) -> None: """ Initialize a DocumentAnalysis object. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified @@ -400,7 +404,7 @@ def __init__(self, *, tones=None, tone_categories=None, warning=None): self.warning = warning @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAnalysis': """Initialize a DocumentAnalysis object from a json dictionary.""" args = {} valid_keys = ['tones', 'tone_categories', 'warning'] @@ -422,7 +426,12 @@ def _from_dict(cls, _dict): args['warning'] = _dict.get('warning') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAnalysis 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, 'tones') and self.tones is not None: @@ -436,17 +445,21 @@ def _to_dict(self): _dict['warning'] = self.warning return _dict - def __str__(self): + 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 DocumentAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAnalysis') -> 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): + def __ne__(self, other: 'DocumentAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -459,12 +472,12 @@ class SentenceAnalysis(): The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :attr str text: The text of the input sentence. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of the request. @@ -476,13 +489,13 @@ class SentenceAnalysis(): """ def __init__(self, - sentence_id, - text, + sentence_id: int, + text: str, *, - tones=None, - tone_categories=None, - input_from=None, - input_to=None): + tones: List['ToneScore'] = None, + tone_categories: List['ToneCategory'] = None, + input_from: int = None, + input_to: int = None) -> None: """ Initialize a SentenceAnalysis object. @@ -490,12 +503,12 @@ def __init__(self, content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :param str text: The text of the input sentence. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of @@ -515,7 +528,7 @@ def __init__(self, self.input_to = input_to @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} valid_keys = [ @@ -554,7 +567,12 @@ def _from_dict(cls, _dict): args['input_to'] = _dict.get('input_to') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentenceAnalysis 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, 'sentence_id') and self.sentence_id is not None: @@ -574,17 +592,21 @@ def _to_dict(self): _dict['input_to'] = self.input_to return _dict - def __str__(self): + 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 SentenceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentenceAnalysis') -> 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): + def __ne__(self, other: 'SentenceAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -595,20 +617,23 @@ class ToneAnalysis(): :attr DocumentAnalysis document_tone: The results of the analysis for the full input content. - :attr list[SentenceAnalysis] sentences_tone: (optional) An array of + :attr List[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the `sentences` parameter of the request is set to `false`. """ - def __init__(self, document_tone, *, sentences_tone=None): + def __init__(self, + document_tone: 'DocumentAnalysis', + *, + sentences_tone: List['SentenceAnalysis'] = None) -> None: """ Initialize a ToneAnalysis object. :param DocumentAnalysis document_tone: The results of the analysis for the full input content. - :param list[SentenceAnalysis] sentences_tone: (optional) An array of + :param List[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the @@ -618,7 +643,7 @@ def __init__(self, document_tone, *, sentences_tone=None): self.sentences_tone = sentences_tone @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneAnalysis': """Initialize a ToneAnalysis object from a json dictionary.""" args = {} valid_keys = ['document_tone', 'sentences_tone'] @@ -641,7 +666,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneAnalysis 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, 'document_tone') and self.document_tone is not None: @@ -652,17 +682,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ToneAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneAnalysis') -> 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): + def __ne__(self, other: 'ToneAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -671,7 +705,7 @@ class ToneCategory(): """ The category for a tone from the input content. - :attr list[ToneScore] tones: An array of `ToneScore` objects that provides the + :attr List[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :attr str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following category IDs: @@ -679,11 +713,12 @@ class ToneCategory(): :attr str category_name: The user-visible, localized name of the category. """ - def __init__(self, tones, category_id, category_name): + def __init__(self, tones: List['ToneScore'], category_id: str, + category_name: str) -> None: """ Initialize a ToneCategory object. - :param list[ToneScore] tones: An array of `ToneScore` objects that provides + :param List[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :param str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following @@ -695,7 +730,7 @@ def __init__(self, tones, category_id, category_name): self.category_name = category_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneCategory': """Initialize a ToneCategory object from a json dictionary.""" args = {} valid_keys = ['tones', 'category_id', 'category_name'] @@ -725,7 +760,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneCategory 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, 'tones') and self.tones is not None: @@ -736,17 +776,21 @@ def _to_dict(self): _dict['category_name'] = self.category_name return _dict - def __str__(self): + 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 ToneCategory object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneCategory') -> 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): + def __ne__(self, other: 'ToneCategory') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -764,7 +808,7 @@ class ToneChatScore(): :attr str tone_name: The user-visible, localized name of the tone. """ - def __init__(self, score, tone_id, tone_name): + def __init__(self, score: float, tone_id: str, tone_name: str) -> None: """ Initialize a ToneChatScore object. @@ -781,7 +825,7 @@ def __init__(self, score, tone_id, tone_name): self.tone_name = tone_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneChatScore': """Initialize a ToneChatScore object from a json dictionary.""" args = {} valid_keys = ['score', 'tone_id', 'tone_name'] @@ -809,7 +853,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneChatScore 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, 'score') and self.score is not None: @@ -820,17 +869,21 @@ def _to_dict(self): _dict['tone_name'] = self.tone_name return _dict - def __str__(self): + 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 ToneChatScore object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneChatScore') -> 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): + def __ne__(self, other: 'ToneChatScore') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -855,7 +908,7 @@ class ToneInput(): :attr str text: The input content that the service is to analyze. """ - def __init__(self, text): + def __init__(self, text: str) -> None: """ Initialize a ToneInput object. @@ -864,7 +917,7 @@ def __init__(self, text): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneInput': """Initialize a ToneInput object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -880,24 +933,33 @@ def _from_dict(cls, _dict): 'Required property \'text\' not present in ToneInput JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneInput 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 __str__(self): + 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 ToneInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneInput') -> 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): + def __ne__(self, other: 'ToneInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -929,7 +991,7 @@ class ToneScore(): :attr str tone_name: The user-visible, localized name of the tone. """ - def __init__(self, score, tone_id, tone_name): + def __init__(self, score: float, tone_id: str, tone_name: str) -> None: """ Initialize a ToneScore object. @@ -960,7 +1022,7 @@ def __init__(self, score, tone_id, tone_name): self.tone_name = tone_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneScore': """Initialize a ToneScore object from a json dictionary.""" args = {} valid_keys = ['score', 'tone_id', 'tone_name'] @@ -986,7 +1048,12 @@ def _from_dict(cls, _dict): 'Required property \'tone_name\' not present in ToneScore JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneScore 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, 'score') and self.score is not None: @@ -997,17 +1064,21 @@ def _to_dict(self): _dict['tone_name'] = self.tone_name return _dict - def __str__(self): + 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 ToneScore object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneScore') -> 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): + def __ne__(self, other: 'ToneScore') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1022,7 +1093,7 @@ class Utterance(): utterance specified by the `text` parameter. """ - def __init__(self, text, *, user=None): + def __init__(self, text: str, *, user: str = None) -> None: """ Initialize a Utterance object. @@ -1035,7 +1106,7 @@ def __init__(self, text, *, user=None): self.user = user @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Utterance': """Initialize a Utterance object from a json dictionary.""" args = {} valid_keys = ['text', 'user'] @@ -1053,7 +1124,12 @@ def _from_dict(cls, _dict): args['user'] = _dict.get('user') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Utterance 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: @@ -1062,17 +1138,21 @@ def _to_dict(self): _dict['user'] = self.user return _dict - def __str__(self): + 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 Utterance object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Utterance') -> 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): + def __ne__(self, other: 'Utterance') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1081,18 +1161,21 @@ class UtteranceAnalyses(): """ The results of the analysis for the utterances of the input content. - :attr list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` + :attr List[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :attr str warning: (optional) **`2017-09-21`:** A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances. **`2016-05-19`:** Not returned. """ - def __init__(self, utterances_tone, *, warning=None): + def __init__(self, + utterances_tone: List['UtteranceAnalysis'], + *, + warning: str = None) -> None: """ Initialize a UtteranceAnalyses object. - :param list[UtteranceAnalysis] utterances_tone: An array of + :param List[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :param str warning: (optional) **`2017-09-21`:** A warning message if the @@ -1103,7 +1186,7 @@ def __init__(self, utterances_tone, *, warning=None): self.warning = warning @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UtteranceAnalyses': """Initialize a UtteranceAnalyses object from a json dictionary.""" args = {} valid_keys = ['utterances_tone', 'warning'] @@ -1125,7 +1208,12 @@ def _from_dict(cls, _dict): args['warning'] = _dict.get('warning') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UtteranceAnalyses 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, @@ -1137,17 +1225,21 @@ def _to_dict(self): _dict['warning'] = self.warning return _dict - def __str__(self): + 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 UtteranceAnalyses object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UtteranceAnalyses') -> 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): + def __ne__(self, other: 'UtteranceAnalyses') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1160,7 +1252,7 @@ class UtteranceAnalysis(): utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :attr str utterance_text: The text of the utterance. - :attr list[ToneChatScore] tones: An array of `ToneChatScore` objects that + :attr List[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. @@ -1169,7 +1261,12 @@ class UtteranceAnalysis(): **`2016-05-19`:** Not returned. """ - def __init__(self, utterance_id, utterance_text, tones, *, error=None): + def __init__(self, + utterance_id: int, + utterance_text: str, + tones: List['ToneChatScore'], + *, + error: str = None) -> None: """ Initialize a UtteranceAnalysis object. @@ -1177,7 +1274,7 @@ def __init__(self, utterance_id, utterance_text, tones, *, error=None): utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :param str utterance_text: The text of the utterance. - :param list[ToneChatScore] tones: An array of `ToneChatScore` objects that + :param List[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. @@ -1191,7 +1288,7 @@ def __init__(self, utterance_id, utterance_text, tones, *, error=None): self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UtteranceAnalysis': """Initialize a UtteranceAnalysis object from a json dictionary.""" args = {} valid_keys = ['utterance_id', 'utterance_text', 'tones', 'error'] @@ -1224,7 +1321,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UtteranceAnalysis 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, 'utterance_id') and self.utterance_id is not None: @@ -1237,16 +1339,20 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 UtteranceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UtteranceAnalysis') -> 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): + def __ne__(self, other: 'UtteranceAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 94e7af5e3..8ff7cb6c4 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,145 +1,258 @@ -# coding: utf-8 -import responses -import ibm_watson -from ibm_watson import ApiException -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -# Simple test, just calling tone() with some text -def test_tone(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = '?version=2016-05-19' - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - tone_analyzer.tone(tone_text.read(), content_type='application/json') - - assert responses.calls[0].request.url == tone_url + tone_args - assert responses.calls[0].response.text == tone_response - - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone() with some modifiers given in 'params': sentences skipped -def test_tone_with_args(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = {'version': '2016-05-19', 'sentences': 'false'} - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) - - assert responses.calls[0].request.url.split('?')[0] == tone_url - # Compare args. Order is not deterministic! - actualArgs = {} - for arg in responses.calls[0].request.url.split('?')[1].split('&'): - actualArgs[arg.split('=')[0]] = arg.split('=')[1] - assert actualArgs == tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone() with some modifiers specified as positional parameters: sentences is false -def test_tone_with_positional_args(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = {'version': '2016-05-19', 'sentences': 'false'} - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) - - assert responses.calls[0].request.url.split('?')[0] == tone_url - # Compare args. Order is not deterministic! - actualArgs = {} - for arg in responses.calls[0].request.url.split('?')[1].split('&'): - actualArgs[arg.split('=')[0]] = arg.split('=')[1] - assert actualArgs == tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone_chat() -def test_tone_chat(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone_chat' - tone_args = '?version=2016-05-19' - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect2.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - utterances = [{'text': 'I am very happy', 'user': 'glenn'}] - tone_analyzer.tone_chat(utterances) - - assert responses.calls[0].request.url == tone_url + tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -######################### -# error response -######################### - - -@responses.activate -def test_error(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - error_code = 400 - error_message = "Invalid JSON input at line 2, column 12" - tone_response = { - "code": error_code, - "sub_code": "C00012", - "error": error_message - } - responses.add(responses.POST, - tone_url, - body=json.dumps(tone_response), - status=error_code, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - - text = 'Team, I know that times are tough!' - try: - tone_analyzer.tone(text, content_type='application/json') - except ApiException as ex: +import pytest +import responses +import ibm_watson.tone_analyzer_v3 +from ibm_watson.tone_analyzer_v3 import * + +base_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' + +############################################################################## +# Start of Service: Methods +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for tone +#----------------------------------------------------------------------------- +class TestTone(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_response(self): + body = self.construct_full_body() + response = fake_response_ToneAnalysis_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ToneAnalysis_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_empty(self): + check_empty_required_params(self, fake_response_ToneAnalysis_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/tone' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = ToneAnalyzerV3( + authenticator=NoAuthAuthenticator(), + version='2017-09-21', + ) + service.set_service_url(base_url) + output = service.tone(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"tone_input": {"mock": "data"}}) + body['content_type'] = "string1" + body['sentences'] = True + body['tones'] = [] + body['content_language'] = "string1" + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({"tone_input": {"mock": "data"}}) + return body + + +#----------------------------------------------------------------------------- +# Test Class for tone_chat +#----------------------------------------------------------------------------- +class TestToneChat(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_chat_response(self): + body = self.construct_full_body() + response = fake_response_UtteranceAnalyses_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_chat_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_UtteranceAnalyses_json + send_request(self, body, response) assert len(responses.calls) == 1 - assert isinstance(ex, ApiException) - assert ex.code == error_code - assert ex.message == error_message + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_chat_empty(self): + check_empty_required_params(self, fake_response_UtteranceAnalyses_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/tone_chat' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = ToneAnalyzerV3( + authenticator=NoAuthAuthenticator(), + version='2017-09-21', + ) + service.set_service_url(base_url) + output = service.tone_chat(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "utterances": [], + }) + body['content_language'] = "string1" + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({ + "utterances": [], + }) + return body + + +# endregion +############################################################################## +# End of Service: Methods +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_ToneAnalysis_json = """{"document_tone": {"tones": [], "tone_categories": [], "warning": "fake_warning"}, "sentences_tone": []}""" +fake_response_UtteranceAnalyses_json = """{"utterances_tone": [], "warning": "fake_warning"}""" From 8ba18c79e6c6825526876d57253750cd26e257a4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:37:10 -0500 Subject: [PATCH 13/28] refactor(vr3): regenerate visual recognition v3 with tests --- ibm_watson/visual_recognition_v3.py | 467 ++++++++----- test/unit/test_visual_recognition_v3.py | 886 ++++++++++++++++++------ 2 files changed, 968 insertions(+), 385 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index bfa038545..da69b5412 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,13 +20,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -36,13 +43,15 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_NAME = 'watson_vision_combined' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Visual Recognition service. @@ -61,25 +70,14 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('visual_recognition') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'visual_recognition') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # General @@ -87,25 +85,25 @@ def __init__( def classify(self, *, - images_file=None, - images_filename=None, - images_file_content_type=None, - url=None, - threshold=None, - owners=None, - classifier_ids=None, - accept_language=None, - **kwargs): + images_file: BinaryIO = None, + images_filename: str = None, + images_file_content_type: str = None, + url: str = None, + threshold: float = None, + owners: str = None, + classifier_ids: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Classify images. Classify images with built-in or custom classifiers. - :param file images_file: (optional) An image file (.gif, .jpg, .png, .tif) - or .zip file with images. Maximum image size is 10 MB. Include no more than - 20 images and limit the .zip file to 100 MB. Encode the image and .zip file - names in UTF-8 if they contain non-ASCII characters. The service assumes - UTF-8 encoding if it encounters non-ASCII characters. + :param TextIO images_file: (optional) An image file (.gif, .jpg, .png, + .tif) or .zip file with images. Maximum image size is 10 MB. Include no + more than 20 images and limit the .zip file to 100 MB. Encode the image and + .zip file names in UTF-8 if they contain non-ASCII characters. The service + assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. :param str images_filename: (optional) The filename for images_file. :param str images_file_content_type: (optional) The content type of @@ -118,7 +116,7 @@ def classify(self, :param float threshold: (optional) The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to return all identified classes. - :param list[str] owners: (optional) The categories of classifiers to apply. + :param List[str] owners: (optional) The categories of classifiers to apply. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - Use `IBM` to classify against the `default` general classifier. You get @@ -129,7 +127,7 @@ def classify(self, classifiers to apply. - Use both `IBM` and `me` to analyze the image against both classifier categories. - :param list[str] classifier_ids: (optional) Which classifiers to apply. + :param List[str] classifier_ids: (optional) Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. @@ -147,8 +145,9 @@ def classify(self, headers = {'Accept-Language': accept_language} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'classify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='classify') headers.update(sdk_headers) params = {'version': self.version} @@ -163,24 +162,26 @@ def classify(self, images_file_content_type or 'application/octet-stream'))) if url: + url = str(url) form_data.append(('url', (None, url, 'text/plain'))) if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'application/json'))) + threshold = str(threshold) + form_data.append(('threshold', (None, threshold, 'text/plain'))) if owners: - owners = self._convert_list(owners) - form_data.append(('owners', (None, owners, 'text/plain'))) + for item in owners: + form_data.append(('owners', (None, item, 'application/json'))) if classifier_ids: - classifier_ids = self._convert_list(classifier_ids) - form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) + for item in classifier_ids: + form_data.append( + ('classifier_ids', (None, item, 'application/json'))) url = '/v3/classify' request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -189,12 +190,12 @@ def classify(self, ######################### def create_classifier(self, - name, - positive_examples, + name: str, + positive_examples: BinaryIO, *, - negative_examples=None, - negative_examples_filename=None, - **kwargs): + negative_examples: BinaryIO = None, + negative_examples_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Create a classifier. @@ -219,14 +220,15 @@ def create_classifier(self, positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class - **goldenretriever**. + **goldenretriever**. The string cannot contain the following characters: + ``$ * - { } \ | / ' " ` [ ]``. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param file negative_examples: (optional) A .zip file of images that do not - depict the visual subject of any of the classes of the new classifier. Must - contain a minimum of 10 images. + :param TextIO negative_examples: (optional) A .zip file of images that do + not depict the visual subject of any of the classes of the new classifier. + Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: (optional) The filename for negative_examples. @@ -243,21 +245,23 @@ def create_classifier(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'create_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='create_classifier') headers.update(sdk_headers) params = {'version': self.version} form_data = [] + name = str(name) form_data.append(('name', (None, name, 'text/plain'))) for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -273,12 +277,13 @@ def create_classifier(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_classifiers(self, *, verbose=None, **kwargs): + def list_classifiers(self, *, verbose: bool = None, + **kwargs) -> 'DetailedResponse': """ Retrieve a list of classifiers. @@ -292,8 +297,9 @@ def list_classifiers(self, *, verbose=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'list_classifiers') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_classifiers') headers.update(sdk_headers) params = {'version': self.version, 'verbose': verbose} @@ -302,12 +308,13 @@ def list_classifiers(self, *, verbose=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_classifier(self, classifier_id, **kwargs): + def get_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Retrieve classifier details. @@ -325,8 +332,9 @@ def get_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'get_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -336,18 +344,18 @@ def get_classifier(self, classifier_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_classifier(self, - classifier_id, + classifier_id: str, *, - positive_examples={}, - negative_examples=None, - negative_examples_filename=None, - **kwargs): + positive_examples: BinaryIO = {}, + negative_examples: BinaryIO = None, + negative_examples_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Update a classifier. @@ -376,14 +384,15 @@ def update_classifier(self, positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class - `goldenretriever`. + `goldenretriever`. The string cannot contain the following characters: ``$ + * - { } \ | / ' " ` [ ]``. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param file negative_examples: (optional) A .zip file of images that do not - depict the visual subject of any of the classes of the new classifier. Must - contain a minimum of 10 images. + :param TextIO negative_examples: (optional) A .zip file of images that do + not depict the visual subject of any of the classes of the new classifier. + Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: (optional) The filename for negative_examples. @@ -398,8 +407,9 @@ def update_classifier(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'update_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='update_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -410,8 +420,8 @@ def update_classifier(self, value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -428,12 +438,13 @@ def update_classifier(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_classifier(self, classifier_id, **kwargs): + def delete_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a classifier. @@ -449,8 +460,9 @@ def delete_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'delete_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -460,8 +472,8 @@ def delete_classifier(self, classifier_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -469,7 +481,8 @@ def delete_classifier(self, classifier_id, **kwargs): # Core ML ######################### - def get_core_ml_model(self, classifier_id, **kwargs): + def get_core_ml_model(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Retrieve a Core ML model of a classifier. @@ -488,8 +501,9 @@ def get_core_ml_model(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'get_core_ml_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_core_ml_model') headers.update(sdk_headers) params = {'version': self.version} @@ -499,8 +513,8 @@ def get_core_ml_model(self, classifier_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -508,7 +522,8 @@ def get_core_ml_model(self, classifier_id, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -532,8 +547,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -542,8 +558,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -579,7 +595,7 @@ class Class(): :attr str class_: The name of the class. """ - def __init__(self, class_): + def __init__(self, class_: str) -> None: """ Initialize a Class object. @@ -588,7 +604,7 @@ def __init__(self, class_): self.class_ = class_ @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Class': """Initialize a Class object from a json dictionary.""" args = {} valid_keys = ['class_', 'class'] @@ -604,24 +620,33 @@ def _from_dict(cls, _dict): 'Required property \'class\' not present in Class JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Class 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, 'class_') and self.class_ is not None: _dict['class'] = self.class_ return _dict - def __str__(self): + 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 Class object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Class') -> 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): + def __ne__(self, other: 'Class') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -644,7 +669,8 @@ class ClassResult(): identified. """ - def __init__(self, class_, score, *, type_hierarchy=None): + def __init__(self, class_: str, score: float, *, + type_hierarchy: str = None) -> None: """ Initialize a ClassResult object. @@ -668,7 +694,7 @@ def __init__(self, class_, score, *, type_hierarchy=None): self.type_hierarchy = type_hierarchy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassResult': """Initialize a ClassResult object from a json dictionary.""" args = {} valid_keys = ['class_', 'class', 'score', 'type_hierarchy'] @@ -691,7 +717,12 @@ def _from_dict(cls, _dict): args['type_hierarchy'] = _dict.get('type_hierarchy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassResult 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, 'class_') and self.class_ is not None: @@ -702,17 +733,21 @@ def _to_dict(self): _dict['type_hierarchy'] = self.type_hierarchy return _dict - def __str__(self): + 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 ClassResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassResult') -> 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): + def __ne__(self, other: 'ClassResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -730,20 +765,20 @@ class ClassifiedImage(): :attr ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. - :attr list[ClassifierResult] classifiers: The classifiers. + :attr List[ClassifierResult] classifiers: The classifiers. """ def __init__(self, - classifiers, + classifiers: List['ClassifierResult'], *, - source_url=None, - resolved_url=None, - image=None, - error=None): + source_url: str = None, + resolved_url: str = None, + image: str = None, + error: 'ErrorInfo' = None) -> None: """ Initialize a ClassifiedImage object. - :param list[ClassifierResult] classifiers: The classifiers. + :param List[ClassifierResult] classifiers: The classifiers. :param str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after @@ -761,7 +796,7 @@ def __init__(self, self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedImage': """Initialize a ClassifiedImage object from a json dictionary.""" args = {} valid_keys = [ @@ -791,7 +826,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedImage 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, 'source_url') and self.source_url is not None: @@ -806,17 +846,21 @@ def _to_dict(self): _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 ClassifiedImage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedImage') -> 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): + def __ne__(self, other: 'ClassifiedImage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -829,28 +873,28 @@ class ClassifiedImages(): images. :attr int images_processed: (optional) Number of images processed for the API call. - :attr list[ClassifiedImage] images: Classified images. - :attr list[WarningInfo] warnings: (optional) Information about what might cause + :attr List[ClassifiedImage] images: Classified images. + :attr List[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ def __init__(self, - images, + images: List['ClassifiedImage'], *, - custom_classes=None, - images_processed=None, - warnings=None): + custom_classes: int = None, + images_processed: int = None, + warnings: List['WarningInfo'] = None) -> None: """ Initialize a ClassifiedImages object. - :param list[ClassifiedImage] images: Classified images. + :param List[ClassifiedImage] images: Classified images. :param int custom_classes: (optional) Number of custom classes identified in the images. :param int images_processed: (optional) Number of images processed for the API call. - :param list[WarningInfo] warnings: (optional) Information about what might + :param List[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. @@ -861,7 +905,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedImages': """Initialize a ClassifiedImages object from a json dictionary.""" args = {} valid_keys = [ @@ -890,7 +934,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedImages 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, 'custom_classes') and self.custom_classes is not None: @@ -904,17 +953,21 @@ def _to_dict(self): _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 ClassifiedImages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedImages') -> 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): + def __ne__(self, other: 'ClassifiedImages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -934,7 +987,7 @@ class Classifier(): might explain why. :attr datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. - :attr list[Class] classes: (optional) Classes that define a classifier. + :attr List[Class] classes: (optional) Classes that define a classifier. :attr datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward compatibility. @@ -944,17 +997,17 @@ class Classifier(): """ def __init__(self, - classifier_id, - name, + classifier_id: str, + name: str, *, - owner=None, - status=None, - core_ml_enabled=None, - explanation=None, - created=None, - classes=None, - retrained=None, - updated=None): + owner: str = None, + status: str = None, + core_ml_enabled: bool = None, + explanation: str = None, + created: datetime = None, + classes: List['Class'] = None, + retrained: datetime = None, + updated: datetime = None) -> None: """ Initialize a Classifier object. @@ -969,7 +1022,7 @@ def __init__(self, field might explain why. :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. - :param list[Class] classes: (optional) Classes that define a classifier. + :param List[Class] classes: (optional) Classes that define a classifier. :param datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward @@ -990,7 +1043,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} valid_keys = [ @@ -1033,7 +1086,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifier 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, 'classifier_id') and self.classifier_id is not None: @@ -1059,17 +1117,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Classifier object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifier') -> 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): + def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1089,23 +1151,24 @@ class ClassifierResult(): :attr str name: Name of the classifier. :attr str classifier_id: ID of a classifier identified in the image. - :attr list[ClassResult] classes: Classes within the classifier. + :attr List[ClassResult] classes: Classes within the classifier. """ - def __init__(self, name, classifier_id, classes): + def __init__(self, name: str, classifier_id: str, + classes: List['ClassResult']) -> None: """ Initialize a ClassifierResult object. :param str name: Name of the classifier. :param str classifier_id: ID of a classifier identified in the image. - :param list[ClassResult] classes: Classes within the classifier. + :param List[ClassResult] classes: Classes within the classifier. """ self.name = name self.classifier_id = classifier_id self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifierResult': """Initialize a ClassifierResult object from a json dictionary.""" args = {} valid_keys = ['name', 'classifier_id', 'classes'] @@ -1136,7 +1199,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierResult 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: @@ -1147,17 +1215,21 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 ClassifierResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifierResult') -> 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): + def __ne__(self, other: 'ClassifierResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1166,19 +1238,19 @@ class Classifiers(): """ A container for the list of classifiers. - :attr list[Classifier] classifiers: List of classifiers. + :attr List[Classifier] classifiers: List of classifiers. """ - def __init__(self, classifiers): + def __init__(self, classifiers: List['Classifier']) -> None: """ Initialize a Classifiers object. - :param list[Classifier] classifiers: List of classifiers. + :param List[Classifier] classifiers: List of classifiers. """ self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifiers': """Initialize a Classifiers object from a json dictionary.""" args = {} valid_keys = ['classifiers'] @@ -1197,24 +1269,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifiers 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, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 Classifiers object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifiers') -> 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): + def __ne__(self, other: 'Classifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1230,7 +1311,7 @@ class ErrorInfo(): :attr str error_id: Codified error string. For example, `limit_exceeded`. """ - def __init__(self, code, description, error_id): + def __init__(self, code: int, description: str, error_id: str) -> None: """ Initialize a ErrorInfo object. @@ -1244,7 +1325,7 @@ def __init__(self, code, description, error_id): self.error_id = error_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ErrorInfo': """Initialize a ErrorInfo object from a json dictionary.""" args = {} valid_keys = ['code', 'description', 'error_id'] @@ -1271,7 +1352,12 @@ def _from_dict(cls, _dict): 'Required property \'error_id\' not present in ErrorInfo JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ErrorInfo 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, 'code') and self.code is not None: @@ -1282,17 +1368,21 @@ def _to_dict(self): _dict['error_id'] = self.error_id return _dict - def __str__(self): + 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 ErrorInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ErrorInfo') -> 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): + def __ne__(self, other: 'ErrorInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1305,7 +1395,7 @@ class WarningInfo(): :attr str description: Information about the error. """ - def __init__(self, warning_id, description): + def __init__(self, warning_id: str, description: str) -> None: """ Initialize a WarningInfo object. @@ -1316,7 +1406,7 @@ def __init__(self, warning_id, description): self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WarningInfo': """Initialize a WarningInfo object from a json dictionary.""" args = {} valid_keys = ['warning_id', 'description'] @@ -1339,7 +1429,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WarningInfo 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, 'warning_id') and self.warning_id is not None: @@ -1348,16 +1443,20 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 WarningInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WarningInfo') -> 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): + def __ne__(self, other: 'WarningInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index d1e879ef5..9aecb805e 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,233 +1,717 @@ -# coding: utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import os -import jwt -import time - -from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -base_url = "https://gateway.watsonplatform.net/visual-recognition/api/" - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestVisualRecognitionV3(TestCase): - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add(responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @responses.activate - def test_get_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') - - response = { - "classifier_id": "bogusnumber", - "name": "Dog Breeds", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "failed", - "created": "2017-08-25T06:39:01.968Z", - "classes": [{"class": "goldenretriever"}] - } - - responses.add(responses.GET, - gc_url, - body=json.dumps(response), - status=200, - content_type='application/json') - vr_service.get_classifier(classifier_id='bogusnumber') - - assert len(responses.calls) == 2 +import pytest +import responses +import tempfile +import ibm_watson.visual_recognition_v3 +from ibm_watson.visual_recognition_v3 import * - @responses.activate - def test_delete_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) +base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') +############################################################################## +# Start of Service: General +############################################################################## +# region - responses.add(responses.DELETE, - gc_url, - body=json.dumps({'response': 200}), - status=200, - content_type='application/json') - vr_service.delete_classifier(classifier_id='bogusnumber') - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for classify +#----------------------------------------------------------------------------- +class TestClassify(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_classifiers(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers') - - response = {"classifiers": [ - { - "classifier_id": "InsuranceClaims_1362331461", - "name": "Insurance Claims", - "status": "ready" - }, - { - "classifier_id": "DogBreeds_1539707331", - "name": "Dog Breeds", - "status": "ready" - } - ]} - - responses.add(responses.GET, - gc_url, + def test_classify_response(self): + body = self.construct_full_body() + response = fake_response_ClassifiedImages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifiedImages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classify' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, body=json.dumps(response), status=200, content_type='application/json') - vr_service.list_classifiers() - - assert len(responses.calls) == 2 + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['images_file'] = tempfile.NamedTemporaryFile() + body['images_filename'] = "string1" + body['images_file_content_type'] = "string1" + body['url'] = "string1" + body['threshold'] = 12345.0 + body['owners'] = [] + body['classifier_ids'] = [] + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: General +############################################################################## + +############################################################################## +# Start of Service: Custom +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_classifier +#----------------------------------------------------------------------------- +class TestCreateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_create_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers') - - response = { - "classifier_id": "DogBreeds_2014254824", - "name": "Dog Breeds", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "failed", - "created": "2017-08-25T06:39:01.968Z", - "classes": [{"class": "goldenretriever"}] - } - + def test_create_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/cars.zip'), 'rb') as cars, \ - open(os.path.join(os.path.dirname(__file__), '../../resources/trucks.zip'), 'rb') as trucks: - vr_service.create_classifier('Cars vs Trucks', positive_examples={'cars': cars}, negative_examples=trucks) - - assert len(responses.calls) == 2 - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.create_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['name'] = "string1" + body['positive_examples'] = {"mock": "data"} + body['negative_examples'] = tempfile.NamedTemporaryFile() + body['negative_examples_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['name'] = "string1" + body['positive_examples'] = {"mock": "data"} + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_classifiers +#----------------------------------------------------------------------------- +class TestListClassifiers(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_update_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusid') - - response = { - "classifier_id": "bogusid", - "name": "Insurance Claims", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "ready", - "created": "2017-07-17T22:17:14.860Z", - "classes": [ - {"class": "motorcycleaccident"}, - {"class": "flattire"}, - {"class": "brokenwinshield"} - ] - } - - responses.add(responses.POST, - gc_url, + def test_list_classifiers_response(self): + body = self.construct_full_body() + response = fake_response_Classifiers_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifiers_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, body=json.dumps(response), status=200, content_type='application/json') - vr_service.update_classifier(classifier_id="bogusid") - assert len(responses.calls) == 2 - - @responses.activate - def test_classify(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classify') - - response = {"images": [ - {"image": "test.jpg", - "classifiers": [ - {"classes": [ - {"score": 0.95, "class": "tiger", "type_hierarchy": "/animal/mammal/carnivore/feline/big cat/tiger"}, - {"score": 0.997, "class": "big cat"}, - {"score": 0.998, "class": "feline"}, - {"score": 0.998, "class": "carnivore"}, - {"score": 0.998, "class": "mammal"}, - {"score": 0.999, "class": "animal"} - ], - "classifier_id": "default", - "name": "default"} - ] - } - ], - "custom_classes": 0, - "images_processed": 1 - } - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.list_classifiers(**body) + return output + + def construct_full_body(self): + body = dict() + body['verbose'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_classifier +#----------------------------------------------------------------------------- +class TestGetClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.get_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_classifier +#----------------------------------------------------------------------------- +class TestUpdateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') - vr_service.classify(parameters='{"url": "http://google.com"}') - - vr_service.classify(parameters=json.dumps({'url': 'http://google.com', 'classifier_ids': ['one', 'two', 'three']})) - vr_service.classify(parameters=json.dumps({'url': 'http://google.com', 'owners': ['me', 'IBM']})) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/test.jpg'), 'rb') as image_file: - vr_service.classify(images_file=image_file) - assert len(responses.calls) == 8 - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.update_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body['positive_examples'] = {"mock": "data"} + body['negative_examples'] = tempfile.NamedTemporaryFile() + body['negative_examples_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_classifier +#----------------------------------------------------------------------------- +class TestDeleteClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_user_data(self): - url = "{0}{1}".format(base_url, 'v3/user_data') - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - response = vr_service.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 2 + def test_delete_classifier_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.delete_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Custom +############################################################################## + +############################################################################## +# Start of Service: CoreML +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for get_core_ml_model +#----------------------------------------------------------------------------- +class TestGetCoreMlModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_core_ml_model_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_core_ml_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_core_ml_model_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}/core_ml_model'.format( + body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.get_core_ml_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CoreML +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=202, + content_type='') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_ClassifiedImages_json = """{"custom_classes": 14, "images_processed": 16, "images": [], "warnings": []}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Classifiers_json = """{"classifiers": []}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" From 652bf7e17f7c773d35f7f66191779c5916202037 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:40:32 -0500 Subject: [PATCH 14/28] chore(vr3): manual changes to vr3 --- ibm_watson/visual_recognition_v3.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index da69b5412..6d0986b7b 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -168,12 +168,11 @@ def classify(self, threshold = str(threshold) form_data.append(('threshold', (None, threshold, 'text/plain'))) if owners: - for item in owners: - form_data.append(('owners', (None, item, 'application/json'))) + owners = self._convert_list(owners) + form_data.append(('owners', (None, owners, 'text/plain'))) if classifier_ids: - for item in classifier_ids: - form_data.append( - ('classifier_ids', (None, item, 'application/json'))) + classifier_ids = self._convert_list(classifier_ids) + form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', From 511c50919024bbebdcad8dc1410e1f6abe1b9f54 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:41:10 -0500 Subject: [PATCH 15/28] refacor(vr4): regenerate visual recognition v4 with tests --- ibm_watson/visual_recognition_v4.py | 910 ++++++++++++++++-------- test/unit/test_visual_recognition_v4.py | 109 ++- 2 files changed, 667 insertions(+), 352 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 7ccad5166..05eb8fd1e 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -34,13 +42,15 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" - default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_NAME = 'watson_vision_combined' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Visual Recognition service. @@ -59,38 +69,27 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('visual_recognition') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'visual_recognition') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Analysis ######################### def analyze(self, - collection_ids, - features, + collection_ids: str, + features: str, *, - images_file=None, - image_url=None, - threshold=None, - **kwargs): + images_file: BinaryIO = None, + image_url: str = None, + threshold: float = None, + **kwargs) -> 'DetailedResponse': """ Analyze images. @@ -101,15 +100,15 @@ def analyze(self, characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. - :param list[str] collection_ids: The IDs of the collections to analyze. - :param list[str] features: The features to analyze. + :param List[str] collection_ids: The IDs of the collections to analyze. + :param List[str] features: The features to analyze. :param list[FileWithMetadata] images_file: (optional) An array of image files (.jpg or .png) or .zip files with images. - Include a maximum of 20 images in a request. - Limit the .zip file to 100 MB. - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) An array of URLs of image files + :param List[str] image_url: (optional) An array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. @@ -132,18 +131,19 @@ def analyze(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', 'analyze') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='analyze') headers.update(sdk_headers) params = {'version': self.version} form_data = [] - if collection_ids: - collection_ids = self._convert_list(collection_ids) - form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) - if features: - features = self._convert_list(features) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append( + ('collection_ids', (None, item, 'application/json'))) + for item in features: + form_data.append(('features', (None, item, 'application/json'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -151,18 +151,19 @@ def analyze(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) + form_data.append( + ('image_url', (None, item, 'application/json'))) if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'application/json'))) + threshold = str(threshold) + form_data.append(('threshold', (None, threshold, 'text/plain'))) url = '/v4/analyze' request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -170,7 +171,11 @@ def analyze(self, # Collections ######################### - def create_collection(self, *, name=None, description=None, **kwargs): + def create_collection(self, + *, + name: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a collection. @@ -192,8 +197,9 @@ def create_collection(self, *, name=None, description=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'create_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='create_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -205,12 +211,12 @@ def create_collection(self, *, name=None, description=None, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_collections(self, **kwargs): + def list_collections(self, **kwargs) -> 'DetailedResponse': """ List collections. @@ -224,8 +230,9 @@ def list_collections(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'list_collections') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='list_collections') headers.update(sdk_headers) params = {'version': self.version} @@ -234,12 +241,13 @@ def list_collections(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_collection(self, collection_id, **kwargs): + def get_collection(self, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get collection details. @@ -257,8 +265,9 @@ def get_collection(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -268,17 +277,17 @@ def get_collection(self, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_collection(self, - collection_id, + collection_id: str, *, - name=None, - description=None, - **kwargs): + name: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Update a collection. @@ -302,8 +311,9 @@ def update_collection(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'update_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='update_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -316,12 +326,13 @@ def update_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_collection(self, collection_id, **kwargs): + def delete_collection(self, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a collection. @@ -339,8 +350,9 @@ def delete_collection(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -350,8 +362,8 @@ def delete_collection(self, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -360,12 +372,12 @@ def delete_collection(self, collection_id, **kwargs): ######################### def add_images(self, - collection_id, + collection_id: str, *, - images_file=None, - image_url=None, - training_data=None, - **kwargs): + images_file: BinaryIO = None, + image_url: str = None, + training_data: str = None, + **kwargs) -> 'DetailedResponse': """ Add images. @@ -381,7 +393,7 @@ def add_images(self, - Limit the .zip file to 100 MB. - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) The array of URLs of image files + :param List[str] image_url: (optional) The array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. @@ -405,8 +417,9 @@ def add_images(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'add_images') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='add_images') headers.update(sdk_headers) params = {'version': self.version} @@ -419,8 +432,10 @@ def add_images(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) + form_data.append( + ('image_url', (None, item, 'application/json'))) if training_data: + training_data = str(training_data) form_data.append( ('training_data', (None, training_data, 'text/plain'))) @@ -430,12 +445,12 @@ def add_images(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_images(self, collection_id, **kwargs): + def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': """ List images. @@ -453,8 +468,9 @@ def list_images(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'list_images') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='list_images') headers.update(sdk_headers) params = {'version': self.version} @@ -464,12 +480,13 @@ def list_images(self, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_image_details(self, collection_id, image_id, **kwargs): + def get_image_details(self, collection_id: str, image_id: str, + **kwargs) -> 'DetailedResponse': """ Get image details. @@ -490,8 +507,9 @@ def get_image_details(self, collection_id, image_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_image_details') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_image_details') headers.update(sdk_headers) params = {'version': self.version} @@ -501,12 +519,13 @@ def get_image_details(self, collection_id, image_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_image(self, collection_id, image_id, **kwargs): + def delete_image(self, collection_id: str, image_id: str, + **kwargs) -> 'DetailedResponse': """ Delete an image. @@ -527,8 +546,9 @@ def delete_image(self, collection_id, image_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_image') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_image') headers.update(sdk_headers) params = {'version': self.version} @@ -538,12 +558,17 @@ def delete_image(self, collection_id, image_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): + def get_jpeg_image(self, + collection_id: str, + image_id: str, + *, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Get a JPEG file of an image. @@ -568,8 +593,9 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_jpeg_image') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_jpeg_image') headers.update(sdk_headers) params = {'version': self.version, 'size': size} @@ -579,8 +605,8 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -588,7 +614,7 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): # Training ######################### - def train(self, collection_id, **kwargs): + def train(self, collection_id: str, **kwargs) -> 'DetailedResponse': """ Train a collection. @@ -608,7 +634,9 @@ def train(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', 'train') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='train') headers.update(sdk_headers) params = {'version': self.version} @@ -618,17 +646,17 @@ def train(self, collection_id, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def add_image_training_data(self, - collection_id, - image_id, + collection_id: str, + image_id: str, *, - objects=None, - **kwargs): + objects: List['TrainingDataObject'] = None, + **kwargs) -> 'DetailedResponse': """ Add training data to an image. @@ -642,7 +670,7 @@ def add_image_training_data(self, :param str collection_id: The identifier of the collection. :param str image_id: The identifier of the image. - :param list[TrainingDataObject] objects: (optional) Training data for + :param List[TrainingDataObject] objects: (optional) Training data for specific objects. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -659,8 +687,9 @@ def add_image_training_data(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'add_image_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='add_image_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -673,12 +702,16 @@ def add_image_training_data(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): + def get_training_usage(self, + *, + start_time: str = None, + end_time: str = None, + **kwargs) -> 'DetailedResponse': """ Get training usage. @@ -700,8 +733,9 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_training_usage') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_training_usage') headers.update(sdk_headers) params = { @@ -714,8 +748,8 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -723,7 +757,8 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -747,8 +782,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -757,8 +793,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -793,19 +829,23 @@ class AnalyzeResponse(): """ Results for all images. - :attr list[Image] images: Analyzed images. - :attr list[Warning] warnings: (optional) Information about what might cause less + :attr List[Image] images: Analyzed images. + :attr List[Warning] warnings: (optional) Information about what might cause less than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ - def __init__(self, images, *, warnings=None, trace=None): + def __init__(self, + images: List['Image'], + *, + warnings: List['Warning'] = None, + trace: str = None) -> None: """ Initialize a AnalyzeResponse object. - :param list[Image] images: Analyzed images. - :param list[Warning] warnings: (optional) Information about what might + :param List[Image] images: Analyzed images. + :param List[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -815,7 +855,7 @@ def __init__(self, images, *, warnings=None, trace=None): self.trace = trace @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalyzeResponse': """Initialize a AnalyzeResponse object from a json dictionary.""" args = {} valid_keys = ['images', 'warnings', 'trace'] @@ -840,7 +880,12 @@ def _from_dict(cls, _dict): args['trace'] = _dict.get('trace') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzeResponse 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, 'images') and self.images is not None: @@ -851,17 +896,21 @@ def _to_dict(self): _dict['trace'] = self.trace return _dict - def __str__(self): + 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 AnalyzeResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalyzeResponse') -> 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): + def __ne__(self, other: 'AnalyzeResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -882,8 +931,9 @@ class Collection(): collection. """ - def __init__(self, collection_id, name, description, created, updated, - image_count, training_status): + def __init__(self, collection_id: str, name: str, description: str, + created: datetime, updated: datetime, image_count: int, + training_status: 'TrainingStatus') -> None: """ Initialize a Collection object. @@ -907,7 +957,7 @@ def __init__(self, collection_id, name, description, created, updated, self.training_status = training_status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = [ @@ -961,7 +1011,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -981,17 +1036,21 @@ def _to_dict(self): _dict['training_status'] = self.training_status._to_dict() return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1001,21 +1060,22 @@ class CollectionObjects(): The objects in a collection that are detected in an image. :attr str collection_id: The identifier of the collection. - :attr list[ObjectDetail] objects: The identified objects in a collection. + :attr List[ObjectDetail] objects: The identified objects in a collection. """ - def __init__(self, collection_id, objects): + def __init__(self, collection_id: str, + objects: List['ObjectDetail']) -> None: """ Initialize a CollectionObjects object. :param str collection_id: The identifier of the collection. - :param list[ObjectDetail] objects: The identified objects in a collection. + :param List[ObjectDetail] objects: The identified objects in a collection. """ self.collection_id = collection_id self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionObjects': """Initialize a CollectionObjects object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'objects'] @@ -1040,7 +1100,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionObjects 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, 'collection_id') and self.collection_id is not None: @@ -1049,17 +1114,21 @@ def _to_dict(self): _dict['objects'] = [x._to_dict() for x in self.objects] return _dict - def __str__(self): + 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 CollectionObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionObjects') -> 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): + def __ne__(self, other: 'CollectionObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1068,20 +1137,20 @@ class CollectionsList(): """ A container for the list of collections. - :attr list[Collection] collections: The collections in this service instance. + :attr List[Collection] collections: The collections in this service instance. """ - def __init__(self, collections): + def __init__(self, collections: List['Collection']) -> None: """ Initialize a CollectionsList object. - :param list[Collection] collections: The collections in this service + :param List[Collection] collections: The collections in this service instance. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionsList': """Initialize a CollectionsList object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1100,24 +1169,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionsList 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 CollectionsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionsList') -> 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): + def __ne__(self, other: 'CollectionsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1126,21 +1204,22 @@ class DetectedObjects(): """ Container for the list of collections that have objects detected in an image. - :attr list[CollectionObjects] collections: (optional) The collections with + :attr List[CollectionObjects] collections: (optional) The collections with identified objects. """ - def __init__(self, *, collections=None): + def __init__(self, *, + collections: List['CollectionObjects'] = None) -> None: """ Initialize a DetectedObjects object. - :param list[CollectionObjects] collections: (optional) The collections with + :param List[CollectionObjects] collections: (optional) The collections with identified objects. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DetectedObjects': """Initialize a DetectedObjects object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1156,24 +1235,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DetectedObjects 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 DetectedObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DetectedObjects') -> 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): + def __ne__(self, other: 'DetectedObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1189,7 +1277,12 @@ class Error(): problem. """ - def __init__(self, code, message, *, more_info=None, target=None): + def __init__(self, + code: str, + message: str, + *, + more_info: str = None, + target: 'ErrorTarget' = None) -> None: """ Initialize a Error object. @@ -1206,7 +1299,7 @@ def __init__(self, code, message, *, more_info=None, target=None): self.target = target @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Error': """Initialize a Error object from a json dictionary.""" args = {} valid_keys = ['code', 'message', 'more_info', 'target'] @@ -1231,7 +1324,12 @@ def _from_dict(cls, _dict): args['target'] = ErrorTarget._from_dict(_dict.get('target')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Error 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, 'code') and self.code is not None: @@ -1244,17 +1342,21 @@ def _to_dict(self): _dict['target'] = self.target._to_dict() return _dict - def __str__(self): + 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 Error object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Error') -> 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): + def __ne__(self, other: 'Error') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1277,7 +1379,7 @@ class ErrorTarget(): :attr str name: The property that is identified with the problem. """ - def __init__(self, type, name): + def __init__(self, type: str, name: str) -> None: """ Initialize a ErrorTarget object. @@ -1289,7 +1391,7 @@ def __init__(self, type, name): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ErrorTarget': """Initialize a ErrorTarget object from a json dictionary.""" args = {} valid_keys = ['type', 'name'] @@ -1310,7 +1412,12 @@ def _from_dict(cls, _dict): 'Required property \'name\' not present in ErrorTarget JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ErrorTarget 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, 'type') and self.type is not None: @@ -1319,17 +1426,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 ErrorTarget object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ErrorTarget') -> 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): + def __ne__(self, other: 'ErrorTarget') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1350,11 +1461,16 @@ class Image(): :attr ImageDimensions dimensions: Height and width of an image. :attr DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :attr list[Error] errors: (optional) A container for the problems in the + :attr List[Error] errors: (optional) A container for the problems in the request. """ - def __init__(self, source, dimensions, objects, *, errors=None): + def __init__(self, + source: 'ImageSource', + dimensions: 'ImageDimensions', + objects: 'DetectedObjects', + *, + errors: List['Error'] = None) -> None: """ Initialize a Image object. @@ -1362,7 +1478,7 @@ def __init__(self, source, dimensions, objects, *, errors=None): :param ImageDimensions dimensions: Height and width of an image. :param DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :param list[Error] errors: (optional) A container for the problems in the + :param List[Error] errors: (optional) A container for the problems in the request. """ self.source = source @@ -1371,7 +1487,7 @@ def __init__(self, source, dimensions, objects, *, errors=None): self.errors = errors @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Image': """Initialize a Image object from a json dictionary.""" args = {} valid_keys = ['source', 'dimensions', 'objects', 'errors'] @@ -1402,7 +1518,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Image 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, 'source') and self.source is not None: @@ -1415,17 +1536,21 @@ def _to_dict(self): _dict['errors'] = [x._to_dict() for x in self.errors] return _dict - def __str__(self): + 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 Image object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Image') -> 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): + def __ne__(self, other: 'Image') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1441,20 +1566,20 @@ class ImageDetails(): (UTC) that the image was created. :attr ImageSource source: The source type of the image. :attr ImageDimensions dimensions: (optional) Height and width of an image. - :attr list[Error] errors: (optional) + :attr List[Error] errors: (optional) :attr TrainingDataObjects training_data: (optional) Training data for all objects. """ def __init__(self, - source, + source: 'ImageSource', *, - image_id=None, - updated=None, - created=None, - dimensions=None, - errors=None, - training_data=None): + image_id: str = None, + updated: datetime = None, + created: datetime = None, + dimensions: 'ImageDimensions' = None, + errors: List['Error'] = None, + training_data: 'TrainingDataObjects' = None) -> None: """ Initialize a ImageDetails object. @@ -1465,7 +1590,7 @@ def __init__(self, :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the image was created. :param ImageDimensions dimensions: (optional) Height and width of an image. - :param list[Error] errors: (optional) + :param List[Error] errors: (optional) :param TrainingDataObjects training_data: (optional) Training data for all objects. """ @@ -1478,7 +1603,7 @@ def __init__(self, self.training_data = training_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDetails': """Initialize a ImageDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -1513,7 +1638,12 @@ def _from_dict(cls, _dict): _dict.get('training_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetails 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, 'image_id') and self.image_id is not None: @@ -1532,17 +1662,21 @@ def _to_dict(self): _dict['training_data'] = self.training_data._to_dict() return _dict - def __str__(self): + 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 ImageDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDetails') -> 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): + def __ne__(self, other: 'ImageDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1551,19 +1685,23 @@ class ImageDetailsList(): """ List of information about the images. - :attr list[ImageDetails] images: (optional) The images in the collection. - :attr list[Warning] warnings: (optional) Information about what might cause less + :attr List[ImageDetails] images: (optional) The images in the collection. + :attr List[Warning] warnings: (optional) Information about what might cause less than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ - def __init__(self, *, images=None, warnings=None, trace=None): + def __init__(self, + *, + images: List['ImageDetails'] = None, + warnings: List['Warning'] = None, + trace: str = None) -> None: """ Initialize a ImageDetailsList object. - :param list[ImageDetails] images: (optional) The images in the collection. - :param list[Warning] warnings: (optional) Information about what might + :param List[ImageDetails] images: (optional) The images in the collection. + :param List[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -1573,7 +1711,7 @@ def __init__(self, *, images=None, warnings=None, trace=None): self.trace = trace @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDetailsList': """Initialize a ImageDetailsList object from a json dictionary.""" args = {} valid_keys = ['images', 'warnings', 'trace'] @@ -1594,7 +1732,12 @@ def _from_dict(cls, _dict): args['trace'] = _dict.get('trace') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetailsList 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, 'images') and self.images is not None: @@ -1605,17 +1748,21 @@ def _to_dict(self): _dict['trace'] = self.trace return _dict - def __str__(self): + 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 ImageDetailsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDetailsList') -> 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): + def __ne__(self, other: 'ImageDetailsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1628,7 +1775,7 @@ class ImageDimensions(): :attr int width: (optional) Width in pixels of the image. """ - def __init__(self, *, height=None, width=None): + def __init__(self, *, height: int = None, width: int = None) -> None: """ Initialize a ImageDimensions object. @@ -1639,7 +1786,7 @@ def __init__(self, *, height=None, width=None): self.width = width @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDimensions': """Initialize a ImageDimensions object from a json dictionary.""" args = {} valid_keys = ['height', 'width'] @@ -1654,7 +1801,12 @@ def _from_dict(cls, _dict): args['width'] = _dict.get('width') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDimensions 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, 'height') and self.height is not None: @@ -1663,17 +1815,21 @@ def _to_dict(self): _dict['width'] = self.width return _dict - def __str__(self): + 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 ImageDimensions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDimensions') -> 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): + def __ne__(self, other: 'ImageDimensions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1694,12 +1850,12 @@ class ImageSource(): """ def __init__(self, - type, + type: str, *, - filename=None, - archive_filename=None, - source_url=None, - resolved_url=None): + filename: str = None, + archive_filename: str = None, + source_url: str = None, + resolved_url: str = None) -> None: """ Initialize a ImageSource object. @@ -1720,7 +1876,7 @@ def __init__(self, self.resolved_url = resolved_url @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSource': """Initialize a ImageSource object from a json dictionary.""" args = {} valid_keys = [ @@ -1746,7 +1902,12 @@ def _from_dict(cls, _dict): args['resolved_url'] = _dict.get('resolved_url') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSource 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, 'type') and self.type is not None: @@ -1762,17 +1923,21 @@ def _to_dict(self): _dict['resolved_url'] = self.resolved_url return _dict - def __str__(self): + 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 ImageSource object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSource') -> 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): + def __ne__(self, other: 'ImageSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1793,7 +1958,8 @@ class ImageSummary(): (UTC) that the image was most recently updated. """ - def __init__(self, *, image_id=None, updated=None): + def __init__(self, *, image_id: str = None, + updated: datetime = None) -> None: """ Initialize a ImageSummary object. @@ -1805,7 +1971,7 @@ def __init__(self, *, image_id=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSummary': """Initialize a ImageSummary object from a json dictionary.""" args = {} valid_keys = ['image_id', 'updated'] @@ -1820,7 +1986,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummary 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, 'image_id') and self.image_id is not None: @@ -1829,17 +2000,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 ImageSummary object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSummary') -> 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): + def __ne__(self, other: 'ImageSummary') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1848,19 +2023,19 @@ class ImageSummaryList(): """ List of images. - :attr list[ImageSummary] images: The images in the collection. + :attr List[ImageSummary] images: The images in the collection. """ - def __init__(self, images): + def __init__(self, images: List['ImageSummary']) -> None: """ Initialize a ImageSummaryList object. - :param list[ImageSummary] images: The images in the collection. + :param List[ImageSummary] images: The images in the collection. """ self.images = images @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSummaryList': """Initialize a ImageSummaryList object from a json dictionary.""" args = {} valid_keys = ['images'] @@ -1879,24 +2054,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummaryList 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, 'images') and self.images is not None: _dict['images'] = [x._to_dict() for x in self.images] return _dict - def __str__(self): + 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 ImageSummaryList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSummaryList') -> 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): + def __ne__(self, other: 'ImageSummaryList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1911,7 +2095,7 @@ class Location(): :attr int height: Height in pixels of the bounding box. """ - def __init__(self, top, left, width, height): + def __init__(self, top: int, left: int, width: int, height: int) -> None: """ Initialize a Location object. @@ -1926,7 +2110,7 @@ def __init__(self, top, left, width, height): self.height = height @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} valid_keys = ['top', 'left', 'width', 'height'] @@ -1957,7 +2141,12 @@ def _from_dict(cls, _dict): 'Required property \'height\' not present in Location JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Location 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, 'top') and self.top is not None: @@ -1970,17 +2159,21 @@ def _to_dict(self): _dict['height'] = self.height return _dict - def __str__(self): + 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 Location object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Location') -> 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): + def __ne__(self, other: 'Location') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1997,7 +2190,7 @@ class ObjectDetail(): location in the image. """ - def __init__(self, object, location, score): + def __init__(self, object: str, location: 'Location', score: float) -> None: """ Initialize a ObjectDetail object. @@ -2013,7 +2206,7 @@ def __init__(self, object, location, score): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ObjectDetail': """Initialize a ObjectDetail object from a json dictionary.""" args = {} valid_keys = ['object', 'location', 'score'] @@ -2040,7 +2233,12 @@ def _from_dict(cls, _dict): 'Required property \'score\' not present in ObjectDetail JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectDetail 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, 'object') and self.object is not None: @@ -2051,17 +2249,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 ObjectDetail object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ObjectDetail') -> 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): + def __ne__(self, other: 'ObjectDetail') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2081,8 +2283,8 @@ class ObjectTrainingStatus(): a success message or information about why training failed. """ - def __init__(self, ready, in_progress, data_changed, latest_failed, - description): + def __init__(self, ready: bool, in_progress: bool, data_changed: bool, + latest_failed: bool, description: str) -> None: """ Initialize a ObjectTrainingStatus object. @@ -2104,7 +2306,7 @@ def __init__(self, ready, in_progress, data_changed, latest_failed, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': """Initialize a ObjectTrainingStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -2148,7 +2350,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectTrainingStatus 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, 'ready') and self.ready is not None: @@ -2163,17 +2370,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 ObjectTrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ObjectTrainingStatus') -> 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): + def __ne__(self, other: 'ObjectTrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2187,7 +2398,8 @@ class TrainingDataObject(): around the object. """ - def __init__(self, *, object=None, location=None): + def __init__(self, *, object: str = None, + location: 'Location' = None) -> None: """ Initialize a TrainingDataObject object. @@ -2199,7 +2411,7 @@ def __init__(self, *, object=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataObject': """Initialize a TrainingDataObject object from a json dictionary.""" args = {} valid_keys = ['object', 'location'] @@ -2214,7 +2426,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObject 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, 'object') and self.object is not None: @@ -2223,17 +2440,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TrainingDataObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataObject') -> 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): + def __ne__(self, other: 'TrainingDataObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2242,21 +2463,21 @@ class TrainingDataObjects(): """ Training data for all objects. - :attr list[TrainingDataObject] objects: (optional) Training data for specific + :attr List[TrainingDataObject] objects: (optional) Training data for specific objects. """ - def __init__(self, *, objects=None): + def __init__(self, *, objects: List['TrainingDataObject'] = None) -> None: """ Initialize a TrainingDataObjects object. - :param list[TrainingDataObject] objects: (optional) Training data for + :param List[TrainingDataObject] objects: (optional) Training data for specific objects. """ self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataObjects': """Initialize a TrainingDataObjects object from a json dictionary.""" args = {} valid_keys = ['objects'] @@ -2271,24 +2492,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObjects 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, 'objects') and self.objects is not None: _dict['objects'] = [x._to_dict() for x in self.objects] return _dict - def __str__(self): + 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 TrainingDataObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataObjects') -> 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): + def __ne__(self, other: 'TrainingDataObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2309,11 +2539,11 @@ class TrainingEvent(): def __init__(self, *, - type=None, - collection_id=None, - completion_time=None, - status=None, - image_count=None): + type: str = None, + collection_id: str = None, + completion_time: datetime = None, + status: str = None, + image_count: int = None) -> None: """ Initialize a TrainingEvent object. @@ -2333,7 +2563,7 @@ def __init__(self, self.image_count = image_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingEvent': """Initialize a TrainingEvent object from a json dictionary.""" args = {} valid_keys = [ @@ -2357,7 +2587,12 @@ def _from_dict(cls, _dict): args['image_count'] = _dict.get('image_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvent 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, 'type') and self.type is not None: @@ -2373,17 +2608,21 @@ def _to_dict(self): _dict['image_count'] = self.image_count return _dict - def __str__(self): + 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 TrainingEvent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingEvent') -> 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): + def __ne__(self, other: 'TrainingEvent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2415,17 +2654,17 @@ class TrainingEvents(): the response for the start and end times. :attr int trained_images: (optional) The total number of images that were used in training for the start and end times. - :attr list[TrainingEvent] events: (optional) The completed training events for + :attr List[TrainingEvent] events: (optional) The completed training events for the start and end time. """ def __init__(self, *, - start_time=None, - end_time=None, - completed_events=None, - trained_images=None, - events=None): + start_time: datetime = None, + end_time: datetime = None, + completed_events: int = None, + trained_images: int = None, + events: List['TrainingEvent'] = None) -> None: """ Initialize a TrainingEvents object. @@ -2439,7 +2678,7 @@ def __init__(self, in the response for the start and end times. :param int trained_images: (optional) The total number of images that were used in training for the start and end times. - :param list[TrainingEvent] events: (optional) The completed training events + :param List[TrainingEvent] events: (optional) The completed training events for the start and end time. """ self.start_time = start_time @@ -2449,7 +2688,7 @@ def __init__(self, self.events = events @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingEvents': """Initialize a TrainingEvents object from a json dictionary.""" args = {} valid_keys = [ @@ -2475,7 +2714,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvents 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, 'start_time') and self.start_time is not None: @@ -2491,17 +2735,21 @@ def _to_dict(self): _dict['events'] = [x._to_dict() for x in self.events] return _dict - def __str__(self): + 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 TrainingEvents object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingEvents') -> 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): + def __ne__(self, other: 'TrainingEvents') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2514,7 +2762,7 @@ class TrainingStatus(): collection. """ - def __init__(self, objects): + def __init__(self, objects: 'ObjectTrainingStatus') -> None: """ Initialize a TrainingStatus object. @@ -2524,7 +2772,7 @@ def __init__(self, objects): self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} valid_keys = ['objects'] @@ -2542,24 +2790,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingStatus 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, 'objects') and self.objects is not None: _dict['objects'] = self.objects._to_dict() return _dict - def __str__(self): + 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 TrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingStatus') -> 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): + def __ne__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2573,7 +2830,8 @@ class Warning(): :attr str more_info: (optional) A URL for more information about the solution. """ - def __init__(self, code, message, *, more_info=None): + def __init__(self, code: str, message: str, *, + more_info: str = None) -> None: """ Initialize a Warning object. @@ -2587,7 +2845,7 @@ def __init__(self, code, message, *, more_info=None): self.more_info = more_info @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} valid_keys = ['code', 'message', 'more_info'] @@ -2610,7 +2868,12 @@ def _from_dict(cls, _dict): args['more_info'] = _dict.get('more_info') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Warning 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, 'code') and self.code is not None: @@ -2621,17 +2884,21 @@ def _to_dict(self): _dict['more_info'] = self.more_info return _dict - def __str__(self): + 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 Warning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Warning') -> 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): + def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2650,16 +2917,20 @@ class FileWithMetadata(): """ A file with its associated metadata. - :attr file data: The data / content for the file. + :attr BinaryIO data: The data / content for the file. :attr str filename: (optional) The filename of the file. :attr str content_type: (optional) The content type of the file. """ - def __init__(self, data, *, filename=None, content_type=None): + def __init__(self, + data: BinaryIO, + *, + filename: str = None, + content_type: str = None) -> None: """ Initialize a FileWithMetadata object. - :param file data: The data / content for the file. + :param BinaryIO data: The data / content for the file. :param str filename: (optional) The filename of the file. :param str content_type: (optional) The content type of the file. """ @@ -2668,7 +2939,7 @@ def __init__(self, data, *, filename=None, content_type=None): self.content_type = content_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FileWithMetadata': """Initialize a FileWithMetadata object from a json dictionary.""" args = {} valid_keys = ['data', 'filename', 'content_type'] @@ -2678,7 +2949,7 @@ def _from_dict(cls, _dict): 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' + ', '.join(bad_keys)) if 'data' in _dict: - args['data'] = file._from_dict(_dict.get('data')) + args['data'] = _dict.get('data') else: raise ValueError( 'Required property \'data\' not present in FileWithMetadata JSON' @@ -2689,7 +2960,12 @@ def _from_dict(cls, _dict): args['content_type'] = _dict.get('content_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FileWithMetadata 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, 'data') and self.data is not None: @@ -2700,16 +2976,20 @@ def _to_dict(self): _dict['content_type'] = self.content_type return _dict - def __str__(self): + 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 FileWithMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FileWithMetadata') -> 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): + def __ne__(self, other: 'FileWithMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 0c408ad30..1a76c2d4e 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,9 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses import tempfile +import ibm_watson.visual_recognition_v4 from ibm_watson.visual_recognition_v4 import * base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' @@ -77,25 +82,27 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.analyze(**body) return output def construct_full_body(self): body = dict() - body['collection_ids'] = ['collection_id1, collection_id2'] - body['features'] = ['test'] - body['image_url'] = ['https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg'] + body['collection_ids'] = [] + body['features'] = [] + body['images_file'] = [] + body['image_url'] = [] body['threshold'] = 12345.0 - body['images_file'] = [FileWithMetadata(tempfile.NamedTemporaryFile())] return body def construct_required_body(self): body = dict() - body['collection_ids'] = ['fake'] - body['features'] = [AnalyzeEnums.Features.OBJECTS.value] + body['collection_ids'] = [] + body['features'] = [] return body @@ -160,8 +167,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.create_collection(**body) return output @@ -233,8 +242,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -299,8 +310,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_collection(**body) return output @@ -367,8 +380,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.update_collection(**body) return output @@ -439,8 +454,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_collection(**body) return output @@ -518,8 +535,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.add_images(**body) return output @@ -589,8 +608,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.list_images(**body) return output @@ -658,8 +679,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_image_details(**body) return output @@ -729,8 +752,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_image(**body) return output @@ -800,8 +825,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_jpeg_image(**body) return output @@ -882,8 +909,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.train(**body) return output @@ -952,8 +981,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.add_image_training_data(**body) return output @@ -1027,8 +1058,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_training_usage(**body) return output @@ -1106,8 +1139,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output From 84269be06baa82b0acc46a01c163917fcd896547 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:52:31 -0500 Subject: [PATCH 16/28] chore(vr4): manual changes to vr4 --- ibm_watson/visual_recognition_v4.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 05eb8fd1e..8139a7a69 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -139,11 +139,10 @@ def analyze(self, params = {'version': self.version} form_data = [] - for item in collection_ids: - form_data.append( - ('collection_ids', (None, item, 'application/json'))) - for item in features: - form_data.append(('features', (None, item, 'application/json'))) + collection_ids = self._convert_list(collection_ids) + form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + features = self._convert_list(features) + form_data.append(('features', (None, features, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -151,8 +150,7 @@ def analyze(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append( - ('image_url', (None, item, 'application/json'))) + form_data.append(('image_url', (None, item, 'text/plain'))) if threshold: threshold = str(threshold) form_data.append(('threshold', (None, threshold, 'text/plain'))) From 776dc8635a98489a9ceb8abf155947bb0f39ad8a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 17:57:54 -0500 Subject: [PATCH 17/28] feat(stt): New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` --- ibm_watson/speech_to_text_v1.py | 73 +++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 22 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 2697d164e..132a7c6cc 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -152,29 +152,31 @@ def get_model(self, model_id, **kwargs): ######################### def recognize(self, - audio, + audio: BinaryIO, *, - content_type=None, - model=None, - language_customization_id=None, - acoustic_customization_id=None, - base_model_version=None, - customization_weight=None, - inactivity_timeout=None, - keywords=None, - keywords_threshold=None, - max_alternatives=None, - word_alternatives_threshold=None, - word_confidence=None, - timestamps=None, - profanity_filter=None, - smart_formatting=None, - speaker_labels=None, - customization_id=None, - grammar_name=None, - redaction=None, - audio_metrics=None, - **kwargs): + 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, + customization_id: str = 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, + **kwargs) -> 'DetailedResponse': """ Recognize audio. @@ -389,6 +391,33 @@ def recognize(self, information about the signal characteristics of the input audio. The service returns audio metrics with the final transcription results. By default, the service returns no audio metrics. + See [Audio + metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#audio_metrics). + :param float end_of_phrase_silence_time: (optional) If `true`, specifies + the duration of the pause interval at which the service splits a transcript + into multiple final results. If the service detects pauses or extended + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + The default pause interval for most languages is 0.8 seconds; the default + for Chinese is 0.6 seconds. + See [End of phrase silence + time](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#silence_time). + :param bool split_transcript_at_phrase_end: (optional) If `true`, directs + the service to split the transcript into multiple final results based on + semantic features of the input, for example, at the conclusion of + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + where the service splits a transcript. By default, the service splits + transcripts based solely on the pause interval. + See [Split transcript at phrase + end](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#split_transcript). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse From 650baa8a48aec6ce75bdfcb370f46d540fac8d89 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:00:13 -0500 Subject: [PATCH 18/28] refactor(stt): regenerate speech to text with tests --- ibm_watson/speech_to_text_v1.py | 1823 ++++++++----- test/unit/test_speech_to_text_v1.py | 3706 ++++++++++++++++++++++----- 2 files changed, 4277 insertions(+), 1252 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 132a7c6cc..b3be2d348 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. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,11 +35,18 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import BinaryIO +from typing import Dict +from typing import List +from typing import TextIO ############################################################################## # Service @@ -49,12 +56,14 @@ class SpeechToTextV1(BaseService): """The Speech to Text V1 service.""" - default_service_url = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_NAME = 'speech_to_text' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Speech to Text service. @@ -62,29 +71,19 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('speech_to_text') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('speech_to_text') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Models ######################### - def list_models(self, **kwargs): + def list_models(self, **kwargs) -> 'DetailedResponse': """ List models. @@ -102,18 +101,18 @@ def list_models(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models') headers.update(sdk_headers) url = '/v1/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_model(self, model_id, **kwargs): + def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Get a model. @@ -136,14 +135,14 @@ def get_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_model') headers.update(sdk_headers) url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response @@ -250,7 +249,7 @@ def recognize(self, **See also:** [Making a multipart HTTP request](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-http#HTTP-multi). - :param file audio: The audio to transcribe. + :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -302,7 +301,7 @@ def recognize(self, submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity timeout](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). - :param list[str] keywords: (optional) An array of keyword strings to spot + :param List[str] keywords: (optional) An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. @@ -429,7 +428,9 @@ def recognize(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'recognize') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='recognize') headers.update(sdk_headers) params = { @@ -451,7 +452,9 @@ def recognize(self, 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, - 'audio_metrics': audio_metrics + 'audio_metrics': audio_metrics, + 'end_of_phrase_silence_time': end_of_phrase_silence_time, + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end } data = audio @@ -461,8 +464,8 @@ def recognize(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -470,7 +473,11 @@ def recognize(self, # Asynchronous ######################### - def register_callback(self, callback_url, *, user_secret=None, **kwargs): + def register_callback(self, + callback_url: str, + *, + user_secret: str = None, + **kwargs) -> 'DetailedResponse': """ Register a callback. @@ -526,8 +533,9 @@ def register_callback(self, callback_url, *, user_secret=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'callback_url': callback_url, 'user_secret': user_secret} @@ -536,12 +544,13 @@ def register_callback(self, callback_url, *, user_secret=None, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def unregister_callback(self, callback_url, **kwargs): + def unregister_callback(self, callback_url: str, + **kwargs) -> 'DetailedResponse': """ Unregister a callback. @@ -563,8 +572,9 @@ def unregister_callback(self, callback_url, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'callback_url': callback_url} @@ -573,41 +583,43 @@ def unregister_callback(self, callback_url, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def create_job(self, - audio, + audio: BinaryIO, *, - content_type=None, - model=None, - callback_url=None, - events=None, - user_token=None, - results_ttl=None, - language_customization_id=None, - acoustic_customization_id=None, - base_model_version=None, - customization_weight=None, - inactivity_timeout=None, - keywords=None, - keywords_threshold=None, - max_alternatives=None, - word_alternatives_threshold=None, - word_confidence=None, - timestamps=None, - profanity_filter=None, - smart_formatting=None, - speaker_labels=None, - customization_id=None, - grammar_name=None, - redaction=None, - processing_metrics=None, - processing_metrics_interval=None, - audio_metrics=None, - **kwargs): + 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, + customization_id: str = 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, + **kwargs) -> 'DetailedResponse': """ Create a job. @@ -694,7 +706,7 @@ def create_job(self, **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). - :param file audio: The audio to transcribe. + :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -782,7 +794,7 @@ def create_job(self, submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity timeout](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). - :param list[str] keywords: (optional) An array of keyword strings to spot + :param List[str] keywords: (optional) An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. @@ -873,6 +885,8 @@ def create_job(self, `processing_metrics_interval` parameter. It also returns processing metrics for transcription events, for example, for final and interim results. By default, the service returns no processing metrics. + See [Processing + metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#processing_metrics). :param float processing_metrics_interval: (optional) Specifies the interval in real wall-clock seconds at which the service is to return processing metrics. The parameter is ignored unless the `processing_metrics` parameter @@ -885,10 +899,39 @@ def create_job(self, intervals, set the value to a large number. If the value is larger than the duration of the audio, the service returns processing metrics only for transcription events. + See [Processing + metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#processing_metrics). :param bool audio_metrics: (optional) If `true`, requests detailed information about the signal characteristics of the input audio. The service returns audio metrics with the final transcription results. By default, the service returns no audio metrics. + See [Audio + metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#audio_metrics). + :param float end_of_phrase_silence_time: (optional) If `true`, specifies + the duration of the pause interval at which the service splits a transcript + into multiple final results. If the service detects pauses or extended + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + The default pause interval for most languages is 0.8 seconds; the default + for Chinese is 0.6 seconds. + See [End of phrase silence + time](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#silence_time). + :param bool split_transcript_at_phrase_end: (optional) If `true`, directs + the service to split the transcript into multiple final results based on + semantic features of the input, for example, at the conclusion of + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + where the service splits a transcript. By default, the service splits + transcripts based solely on the pause interval. + See [Split transcript at phrase + end](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#split_transcript). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -900,7 +943,9 @@ def create_job(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = { @@ -928,7 +973,9 @@ def create_job(self, 'redaction': redaction, 'processing_metrics': processing_metrics, 'processing_metrics_interval': processing_metrics_interval, - 'audio_metrics': audio_metrics + 'audio_metrics': audio_metrics, + 'end_of_phrase_silence_time': end_of_phrase_silence_time, + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end } data = audio @@ -938,12 +985,12 @@ def create_job(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def check_jobs(self, **kwargs): + def check_jobs(self, **kwargs) -> 'DetailedResponse': """ Check jobs. @@ -966,18 +1013,18 @@ def check_jobs(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'check_jobs') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_jobs') headers.update(sdk_headers) url = '/v1/recognitions' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def check_job(self, id, **kwargs): + def check_job(self, id: str, **kwargs) -> 'DetailedResponse': """ Check a job. @@ -1008,18 +1055,18 @@ def check_job(self, id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'check_job') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_job') headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_job(self, id, **kwargs): + def delete_job(self, id: str, **kwargs) -> 'DetailedResponse': """ Delete a job. @@ -1045,14 +1092,16 @@ def delete_job(self, id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_job') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_job') headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -1061,12 +1110,12 @@ def delete_job(self, id, **kwargs): ######################### def create_language_model(self, - name, - base_model_name, + name: str, + base_model_name: str, *, - dialect=None, - description=None, - **kwargs): + dialect: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom language model. @@ -1074,9 +1123,9 @@ def create_language_model(self, language model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. - You can create a maximum of 1024 custom language models, per credential. The - service returns an error if you attempt to create more than 1024 models. You do - not lose any models, but you cannot create any more until your model count is + You can create a maximum of 1024 custom language models per owning credentials. + The service returns an error if you attempt to create more than 1024 models. You + do not lose any models, but you cannot create any more until your model count is below the limit. **See also:** [Create a custom language model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#createModel-language). @@ -1128,8 +1177,9 @@ def create_language_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = { @@ -1143,12 +1193,13 @@ def create_language_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_language_models(self, *, language=None, **kwargs): + def list_language_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom language models. @@ -1172,8 +1223,9 @@ def list_language_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'language': language} @@ -1182,12 +1234,13 @@ def list_language_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_language_model(self, customization_id, **kwargs): + def get_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom language model. @@ -1211,20 +1264,20 @@ def get_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_language_model(self, customization_id, **kwargs): + def delete_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom language model. @@ -1250,25 +1303,26 @@ def delete_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response def train_language_model(self, - customization_id, + customization_id: str, *, - word_type_to_add=None, - customization_weight=None, - **kwargs): + word_type_to_add: str = None, + customization_weight: float = None, + **kwargs) -> 'DetailedResponse': """ Train a custom language model. @@ -1338,8 +1392,9 @@ def train_language_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = { @@ -1352,12 +1407,13 @@ def train_language_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def reset_language_model(self, customization_id, **kwargs): + def reset_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Reset a custom language model. @@ -1385,20 +1441,20 @@ def reset_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response - def upgrade_language_model(self, customization_id, **kwargs): + def upgrade_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Upgrade a custom language model. @@ -1434,16 +1490,15 @@ def upgrade_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response @@ -1451,7 +1506,8 @@ def upgrade_language_model(self, customization_id, **kwargs): # Custom corpora ######################### - def list_corpora(self, customization_id, **kwargs): + def list_corpora(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ List corpora. @@ -1477,25 +1533,25 @@ def list_corpora(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_corpora') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_corpora') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_corpus(self, - customization_id, - corpus_name, - corpus_file, + customization_id: str, + corpus_name: str, + corpus_file: BinaryIO, *, - allow_overwrite=None, - **kwargs): + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a corpus. @@ -1558,8 +1614,8 @@ def add_corpus(self, custom words that are added or modified by the user. * Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service. - :param file corpus_file: A plain text file that contains the training data - for the corpus. Encode the file in UTF-8 if it contains non-ASCII + :param TextIO corpus_file: A plain text file that contains the training + data for the corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service assumes UTF-8 encoding if it encounters non-ASCII characters. Make sure that you know the character encoding of the file. You must use @@ -1587,7 +1643,9 @@ def add_corpus(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = {'allow_overwrite': allow_overwrite} @@ -1601,12 +1659,13 @@ def add_corpus(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_corpus(self, customization_id, corpus_name, **kwargs): + def get_corpus(self, customization_id: str, corpus_name: str, + **kwargs) -> 'DetailedResponse': """ Get a corpus. @@ -1636,19 +1695,20 @@ def get_corpus(self, customization_id, corpus_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_corpus') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_corpus') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_corpus(self, customization_id, corpus_name, **kwargs): + def delete_corpus(self, customization_id: str, corpus_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a corpus. @@ -1682,15 +1742,17 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_corpus') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_corpus') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -1699,11 +1761,11 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): ######################### def list_words(self, - customization_id, + customization_id: str, *, - word_type=None, - sort=None, - **kwargs): + word_type: str = None, + sort: str = None, + **kwargs) -> 'DetailedResponse': """ List custom words. @@ -1747,7 +1809,9 @@ def list_words(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = {'word_type': word_type, 'sort': sort} @@ -1757,12 +1821,13 @@ def list_words(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def add_words(self, customization_id, words, **kwargs): + def add_words(self, customization_id: str, words: List['CustomWord'], + **kwargs) -> 'DetailedResponse': """ Add custom words. @@ -1819,7 +1884,7 @@ def add_words(self, customization_id, words, **kwargs): language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. - :param list[CustomWord] words: An array of `CustomWord` objects that + :param List[CustomWord] words: An array of `CustomWord` objects that provides information about each custom word that is to be added to or updated in the custom language model. :param dict headers: A `dict` containing the request headers @@ -1836,7 +1901,9 @@ def add_words(self, customization_id, words, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = {'words': words} @@ -1846,19 +1913,19 @@ def add_words(self, customization_id, words, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def add_word(self, - customization_id, - word_name, + customization_id: str, + word_name: str, *, - word=None, - sounds_like=None, - display_as=None, - **kwargs): + word: str = None, + sounds_like: List[str] = None, + display_as: str = None, + **kwargs) -> 'DetailedResponse': """ Add a custom word. @@ -1910,7 +1977,7 @@ def add_word(self, model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: (optional) An array of sounds-like + :param List[str] sounds_like: (optional) An 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 a word that is not in the service's base vocabulary, omit the @@ -1939,7 +2006,9 @@ def add_word(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = { @@ -1953,12 +2022,13 @@ def add_word(self, request = self.prepare_request(method='PUT', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_word(self, customization_id, word_name, **kwargs): + def get_word(self, customization_id: str, word_name: str, + **kwargs) -> 'DetailedResponse': """ Get a custom word. @@ -1989,19 +2059,20 @@ def get_word(self, customization_id, word_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_word(self, customization_id, word_name, **kwargs): + def delete_word(self, customization_id: str, word_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom word. @@ -2036,15 +2107,17 @@ def delete_word(self, customization_id, word_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -2052,7 +2125,8 @@ def delete_word(self, customization_id, word_name, **kwargs): # Custom grammars ######################### - def list_grammars(self, customization_id, **kwargs): + def list_grammars(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ List grammars. @@ -2078,26 +2152,26 @@ def list_grammars(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_grammars') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_grammars') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_grammar(self, - customization_id, - grammar_name, - grammar_file, - content_type, + customization_id: str, + grammar_name: str, + grammar_file: str, + content_type: str, *, - allow_overwrite=None, - **kwargs): + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a grammar. @@ -2189,7 +2263,9 @@ def add_grammar(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = {'allow_overwrite': allow_overwrite} @@ -2202,12 +2278,13 @@ def add_grammar(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_grammar(self, customization_id, grammar_name, **kwargs): + def get_grammar(self, customization_id: str, grammar_name: str, + **kwargs) -> 'DetailedResponse': """ Get a grammar. @@ -2237,19 +2314,20 @@ def get_grammar(self, customization_id, grammar_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_grammar') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_grammar') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_grammar(self, customization_id, grammar_name, **kwargs): + def delete_grammar(self, customization_id: str, grammar_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a grammar. @@ -2282,15 +2360,17 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_grammar') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_grammar') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -2299,11 +2379,11 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): ######################### def create_acoustic_model(self, - name, - base_model_name, + name: str, + base_model_name: str, *, - description=None, - **kwargs): + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom acoustic model. @@ -2311,9 +2391,9 @@ def create_acoustic_model(self, acoustic model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. - You can create a maximum of 1024 custom acoustic models, per credential. The - service returns an error if you attempt to create more than 1024 models. You do - not lose any models, but you cannot create any more until your model count is + You can create a maximum of 1024 custom acoustic models per owning credentials. + The service returns an error if you attempt to create more than 1024 models. You + do not lose any models, but you cannot create any more until your model count is below the limit. **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). @@ -2345,8 +2425,9 @@ def create_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = { @@ -2359,12 +2440,13 @@ def create_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_acoustic_models(self, *, language=None, **kwargs): + def list_acoustic_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom acoustic models. @@ -2388,8 +2470,9 @@ def list_acoustic_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'language': language} @@ -2398,12 +2481,13 @@ def list_acoustic_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_acoustic_model(self, customization_id, **kwargs): + def get_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom acoustic model. @@ -2427,20 +2511,20 @@ def get_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_acoustic_model(self, customization_id, **kwargs): + def delete_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom acoustic model. @@ -2466,24 +2550,25 @@ def delete_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response def train_acoustic_model(self, - customization_id, + customization_id: str, *, - custom_language_model_id=None, - **kwargs): + custom_language_model_id: str = None, + **kwargs) -> 'DetailedResponse': """ Train a custom acoustic model. @@ -2557,8 +2642,9 @@ def train_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'custom_language_model_id': custom_language_model_id} @@ -2568,12 +2654,13 @@ def train_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def reset_acoustic_model(self, customization_id, **kwargs): + def reset_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Reset a custom acoustic model. @@ -2603,25 +2690,24 @@ def reset_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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) url = '/v1/acoustic_customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response def upgrade_acoustic_model(self, - customization_id, + customization_id: str, *, - custom_language_model_id=None, - force=None, - **kwargs): + custom_language_model_id: str = None, + force: bool = None, + **kwargs) -> 'DetailedResponse': """ Upgrade a custom acoustic model. @@ -2677,8 +2763,9 @@ def upgrade_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = { @@ -2691,8 +2778,8 @@ def upgrade_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2700,7 +2787,7 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id, **kwargs): + def list_audio(self, customization_id: str, **kwargs) -> 'DetailedResponse': """ List audio resources. @@ -2728,27 +2815,27 @@ def list_audio(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_audio(self, - customization_id, - audio_name, - audio_resource, + customization_id: str, + audio_name: str, + audio_resource: BinaryIO, *, - content_type=None, - contained_content_type=None, - allow_overwrite=None, - **kwargs): + content_type: str = None, + contained_content_type: str = None, + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add an audio resource. @@ -2853,8 +2940,8 @@ def add_audio(self, URL-encoded wherever used, their use is strongly discouraged.) * Do not use the name of an audio resource that has already been added to the custom model. - :param file audio_resource: The audio resource that is to be added to the - custom acoustic model, an individual audio file or an archive file. + :param BinaryIO audio_resource: The audio resource that is to be added to + the custom acoustic model, an individual audio file or an archive file. With the `curl` command, use the `--data-binary` option to upload the file for the request. :param str content_type: (optional) For an audio-type resource, the format @@ -2899,7 +2986,9 @@ def add_audio(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', '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 = {'allow_overwrite': allow_overwrite} @@ -2912,12 +3001,13 @@ def add_audio(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_audio(self, customization_id, audio_name, **kwargs): + def get_audio(self, customization_id: str, audio_name: str, + **kwargs) -> 'DetailedResponse': """ Get an audio resource. @@ -2961,19 +3051,20 @@ def get_audio(self, customization_id, audio_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_audio(self, customization_id, audio_name, **kwargs): + def delete_audio(self, customization_id: str, audio_name: str, + **kwargs) -> 'DetailedResponse': """ Delete an audio resource. @@ -3007,15 +3098,17 @@ def delete_audio(self, customization_id, audio_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -3023,7 +3116,8 @@ def delete_audio(self, customization_id, audio_name, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -3050,8 +3144,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - '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 = {'customer_id': customer_id} @@ -3060,8 +3155,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -3095,10 +3190,14 @@ class ModelId(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3157,10 +3256,14 @@ class Model(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3219,10 +3322,14 @@ class Model(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3397,7 +3504,7 @@ class AcousticModel(): (YYYY-MM-DDThh:mm:ss.sTZD). :attr 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 + :attr 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; otherwise, only a single version is shown. @@ -3429,19 +3536,19 @@ class AcousticModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - created=None, - updated=None, - language=None, - versions=None, - owner=None, - name=None, - description=None, - base_model_name=None, - status=None, - progress=None, - warnings=None): + 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: """ Initialize a AcousticModel object. @@ -3458,7 +3565,7 @@ def __init__(self, format (YYYY-MM-DDThh:mm:ss.sTZD). :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :param list[str] versions: (optional) A list of the available versions of + :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; otherwise, only a single @@ -3505,7 +3612,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} valid_keys = [ @@ -3548,7 +3655,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AcousticModel 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, @@ -3579,17 +3691,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 AcousticModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AcousticModel') -> 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): + def __ne__(self, other: 'AcousticModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3618,18 +3734,18 @@ class AcousticModels(): """ Information about existing custom acoustic models. - :attr list[AcousticModel] customizations: An array of `AcousticModel` objects + :attr 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): + def __init__(self, customizations: List['AcousticModel']) -> None: """ Initialize a AcousticModels object. - :param list[AcousticModel] customizations: An array of `AcousticModel` + :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 @@ -3638,7 +3754,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -3658,7 +3774,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AcousticModels 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, 'customizations') and self.customizations is not None: @@ -3667,17 +3788,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 AcousticModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AcousticModels') -> 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): + def __ne__(self, other: 'AcousticModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3707,10 +3832,10 @@ class AudioDetails(): def __init__(self, *, - type=None, - codec=None, - frequency=None, - compression=None): + type: str = None, + codec: str = None, + frequency: int = None, + compression: str = None) -> None: """ Initialize a AudioDetails object. @@ -3738,7 +3863,7 @@ def __init__(self, self.compression = compression @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} valid_keys = ['type', 'codec', 'frequency', 'compression'] @@ -3757,7 +3882,12 @@ def _from_dict(cls, _dict): args['compression'] = _dict.get('compression') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioDetails 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, 'type') and self.type is not None: @@ -3770,17 +3900,21 @@ def _to_dict(self): _dict['compression'] = self.compression return _dict - def __str__(self): + 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 AudioDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioDetails') -> 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): + def __ne__(self, other: 'AudioDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3834,7 +3968,7 @@ class AudioListing(): :attr 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 + :attr 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. @@ -3842,12 +3976,12 @@ class AudioListing(): def __init__(self, *, - duration=None, - name=None, - details=None, - status=None, - container=None, - audio=None): + duration: int = None, + name: str = None, + details: 'AudioDetails' = None, + status: str = None, + container: 'AudioResource' = None, + audio: List['AudioResource'] = None) -> None: """ Initialize a AudioListing object. @@ -3873,7 +4007,7 @@ def __init__(self, :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. - :param list[AudioResource] audio: (optional) **For an archive-type + :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. @@ -3886,7 +4020,7 @@ def __init__(self, self.audio = audio @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} valid_keys = [ @@ -3913,7 +4047,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioListing 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, 'duration') and self.duration is not None: @@ -3930,17 +4069,21 @@ def _to_dict(self): _dict['audio'] = [x._to_dict() for x in self.audio] return _dict - def __str__(self): + 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 AudioListing object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioListing') -> 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): + def __ne__(self, other: 'AudioListing') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3975,7 +4118,8 @@ class AudioMetrics(): characteristics of the input audio. """ - def __init__(self, sampling_interval, accumulated): + def __init__(self, sampling_interval: float, + accumulated: 'AudioMetricsDetails') -> None: """ Initialize a AudioMetrics object. @@ -3991,7 +4135,7 @@ def __init__(self, sampling_interval, accumulated): self.accumulated = accumulated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} valid_keys = ['sampling_interval', 'accumulated'] @@ -4015,7 +4159,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetrics 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, @@ -4025,17 +4174,21 @@ def _to_dict(self): _dict['accumulated'] = self.accumulated._to_dict() return _dict - def __str__(self): + 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 AudioMetrics object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetrics') -> 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): + def __ne__(self, other: 'AudioMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4064,10 +4217,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 + :attr 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 + :attr 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 @@ -4075,12 +4228,12 @@ 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 + :attr 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 + :attr 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 @@ -4088,16 +4241,16 @@ class AudioMetricsDetails(): """ def __init__(self, - final, - end_time, - speech_ratio, - high_frequency_loss, - direct_current_offset, - clipping_rate, - speech_level, - non_speech_level, + 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=None): + signal_to_noise_ratio: float = None) -> None: """ Initialize a AudioMetricsDetails object. @@ -4117,10 +4270,10 @@ def __init__(self, full spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :param 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. - :param 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 @@ -4128,12 +4281,12 @@ def __init__(self, 16-bit Pulse-Code 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. - :param 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). - :param 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 @@ -4155,7 +4308,7 @@ def __init__(self, self.non_speech_level = non_speech_level @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -4232,7 +4385,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetricsDetails 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, 'final') and self.final is not None: @@ -4264,17 +4422,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 AudioMetricsDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetricsDetails') -> 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): + def __ne__(self, other: 'AudioMetricsDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4291,7 +4453,7 @@ class AudioMetricsHistogramBin(): :attr int count: The number of values in the bin of the histogram. """ - def __init__(self, begin, end, count): + def __init__(self, begin: float, end: float, count: int) -> None: """ Initialize a AudioMetricsHistogramBin object. @@ -4304,7 +4466,7 @@ def __init__(self, begin, end, count): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} valid_keys = ['begin', 'end', 'count'] @@ -4333,7 +4495,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetricsHistogramBin 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, 'begin') and self.begin is not None: @@ -4344,17 +4511,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 AudioMetricsHistogramBin object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetricsHistogramBin') -> 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): + def __ne__(self, other: 'AudioMetricsHistogramBin') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4384,7 +4555,8 @@ class AudioResource(): invalid. """ - def __init__(self, duration, name, details, status): + def __init__(self, duration: int, name: str, details: 'AudioDetails', + status: str) -> None: """ Initialize a AudioResource object. @@ -4414,7 +4586,7 @@ def __init__(self, duration, name, details, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} valid_keys = ['duration', 'name', 'details', 'status'] @@ -4448,7 +4620,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioResource 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, 'duration') and self.duration is not None: @@ -4461,17 +4638,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 AudioResource object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioResource') -> 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): + def __ne__(self, other: 'AudioResource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4501,12 +4682,13 @@ class AudioResources(): 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 + :attr 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, audio): + def __init__(self, total_minutes_of_audio: float, + audio: List['AudioResource']) -> None: """ Initialize a AudioResources object. @@ -4514,7 +4696,7 @@ def __init__(self, total_minutes_of_audio, 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. - :param 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. """ @@ -4522,7 +4704,7 @@ def __init__(self, total_minutes_of_audio, audio): self.audio = audio @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} valid_keys = ['total_minutes_of_audio', 'audio'] @@ -4547,7 +4729,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioResources 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, 'total_minutes_of_audio' @@ -4557,17 +4744,21 @@ def _to_dict(self): _dict['audio'] = [x._to_dict() for x in self.audio] return _dict - def __str__(self): + 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 AudioResources object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioResources') -> 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): + def __ne__(self, other: 'AudioResources') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4576,23 +4767,23 @@ class Corpora(): """ Information about the corpora from a custom language model. - :attr list[Corpus] corpora: An array of `Corpus` objects that provides + :attr 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): + def __init__(self, corpora: List['Corpus']) -> None: """ Initialize a Corpora object. - :param 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. """ self.corpora = corpora @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} valid_keys = ['corpora'] @@ -4610,24 +4801,33 @@ def _from_dict(cls, _dict): 'Required property \'corpora\' not present in Corpora JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Corpora 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, 'corpora') and self.corpora is not None: _dict['corpora'] = [x._to_dict() for x in self.corpora] return _dict - def __str__(self): + 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 Corpora object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Corpora') -> 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): + def __ne__(self, other: 'Corpora') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4654,12 +4854,12 @@ class Corpus(): """ def __init__(self, - name, - total_words, - out_of_vocabulary_words, - status, + name: str, + total_words: int, + out_of_vocabulary_words: int, + status: str, *, - error=None): + error: str = None) -> None: """ Initialize a Corpus object. @@ -4686,7 +4886,7 @@ def __init__(self, self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} valid_keys = [ @@ -4723,7 +4923,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Corpus 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: @@ -4739,17 +4944,21 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 Corpus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Corpus') -> 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): + def __ne__(self, other: 'Corpus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4777,7 +4986,7 @@ class CustomWord(): include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :attr list[str] sounds_like: (optional) An array of sounds-like pronunciations + :attr List[str] sounds_like: (optional) An 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 a word that is not in the service's base vocabulary, omit the parameter to @@ -4795,7 +5004,11 @@ class CustomWord(): spelling in corpora training data. """ - def __init__(self, *, word=None, sounds_like=None, display_as=None): + def __init__(self, + *, + word: str = None, + sounds_like: List[str] = None, + display_as: str = None) -> None: """ Initialize a CustomWord object. @@ -4804,7 +5017,7 @@ def __init__(self, *, word=None, sounds_like=None, display_as=None): model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: (optional) An array of sounds-like + :param List[str] sounds_like: (optional) An 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 a word that is not in the service's base vocabulary, omit the @@ -4826,7 +5039,7 @@ def __init__(self, *, word=None, sounds_like=None, display_as=None): self.display_as = display_as @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} valid_keys = ['word', 'sounds_like', 'display_as'] @@ -4843,7 +5056,12 @@ def _from_dict(cls, _dict): args['display_as'] = _dict.get('display_as') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CustomWord 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, 'word') and self.word is not None: @@ -4854,17 +5072,21 @@ def _to_dict(self): _dict['display_as'] = self.display_as return _dict - def __str__(self): + 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 CustomWord object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CustomWord') -> 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): + def __ne__(self, other: 'CustomWord') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4889,7 +5111,12 @@ class Grammar(): flag to 'true'.`. """ - def __init__(self, name, out_of_vocabulary_words, status, *, error=None): + def __init__(self, + name: str, + out_of_vocabulary_words: int, + status: str, + *, + error: str = None) -> None: """ Initialize a Grammar object. @@ -4915,7 +5142,7 @@ def __init__(self, name, out_of_vocabulary_words, status, *, error=None): self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} valid_keys = ['name', 'out_of_vocabulary_words', 'status', 'error'] @@ -4945,7 +5172,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Grammar 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: @@ -4959,17 +5191,21 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 Grammar object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Grammar') -> 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): + def __ne__(self, other: 'Grammar') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4992,23 +5228,23 @@ class Grammars(): """ Information about the grammars from a custom language model. - :attr list[Grammar] grammars: An array of `Grammar` objects that provides + :attr 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): + def __init__(self, grammars: List['Grammar']) -> None: """ Initialize a Grammars object. - :param 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. """ self.grammars = grammars @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} valid_keys = ['grammars'] @@ -5026,24 +5262,33 @@ def _from_dict(cls, _dict): 'Required property \'grammars\' not present in Grammars JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Grammars 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, 'grammars') and self.grammars is not None: _dict['grammars'] = [x._to_dict() for x in self.grammars] return _dict - def __str__(self): + 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 Grammars object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Grammars') -> 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): + def __ne__(self, other: 'Grammars') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5060,7 +5305,8 @@ class KeywordResult(): 0.0 to 1.0. """ - def __init__(self, normalized_text, start_time, end_time, confidence): + def __init__(self, normalized_text: str, start_time: float, end_time: float, + confidence: float) -> None: """ Initialize a KeywordResult object. @@ -5077,7 +5323,7 @@ def __init__(self, normalized_text, start_time, end_time, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} valid_keys = ['normalized_text', 'start_time', 'end_time', 'confidence'] @@ -5112,7 +5358,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordResult 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, @@ -5126,17 +5377,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 KeywordResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordResult') -> 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): + def __ne__(self, other: 'KeywordResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5168,7 +5423,7 @@ 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 + :attr 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; otherwise, only a single version is shown. @@ -5204,21 +5459,21 @@ class LanguageModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - created=None, - updated=None, - language=None, - dialect=None, - versions=None, - owner=None, - name=None, - description=None, - base_model_name=None, - status=None, - progress=None, - error=None, - warnings=None): + 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: """ Initialize a LanguageModel object. @@ -5245,7 +5500,7 @@ def __init__(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :param list[str] versions: (optional) A list of the available versions of + :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; otherwise, only a single @@ -5299,7 +5554,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} valid_keys = [ @@ -5346,7 +5601,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageModel 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, @@ -5381,17 +5641,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 LanguageModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LanguageModel') -> 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): + def __ne__(self, other: 'LanguageModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5420,18 +5684,18 @@ class LanguageModels(): """ Information about existing custom language models. - :attr list[LanguageModel] customizations: An array of `LanguageModel` objects + :attr 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): + def __init__(self, customizations: List['LanguageModel']) -> None: """ Initialize a LanguageModels object. - :param list[LanguageModel] customizations: An array of `LanguageModel` + :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 @@ -5440,7 +5704,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -5460,7 +5724,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageModels 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, 'customizations') and self.customizations is not None: @@ -5469,17 +5738,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 LanguageModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LanguageModels') -> 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): + def __ne__(self, other: 'LanguageModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5511,11 +5784,11 @@ class ProcessedAudio(): """ def __init__(self, - received, - seen_by_engine, - transcription, + received: float, + seen_by_engine: float, + transcription: float, *, - speaker_labels=None): + speaker_labels: float = None) -> None: """ Initialize a ProcessedAudio object. @@ -5549,7 +5822,7 @@ def __init__(self, self.speaker_labels = speaker_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} valid_keys = [ @@ -5582,7 +5855,12 @@ def _from_dict(cls, _dict): args['speaker_labels'] = _dict.get('speaker_labels') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProcessedAudio 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, 'received') and self.received is not None: @@ -5595,17 +5873,21 @@ def _to_dict(self): _dict['speaker_labels'] = self.speaker_labels return _dict - def __str__(self): + 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 ProcessedAudio object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ProcessedAudio') -> 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): + def __ne__(self, other: 'ProcessedAudio') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5638,8 +5920,9 @@ class ProcessingMetrics(): different results if necessary. """ - def __init__(self, processed_audio, wall_clock_since_first_byte_received, - periodic): + def __init__(self, processed_audio: 'ProcessedAudio', + wall_clock_since_first_byte_received: float, + periodic: bool) -> None: """ Initialize a ProcessingMetrics object. @@ -5669,7 +5952,7 @@ def __init__(self, processed_audio, wall_clock_since_first_byte_received, self.periodic = periodic @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} valid_keys = [ @@ -5703,7 +5986,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProcessingMetrics 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, @@ -5717,17 +6005,21 @@ def _to_dict(self): _dict['periodic'] = self.periodic return _dict - def __str__(self): + 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 ProcessingMetrics object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ProcessingMetrics') -> 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): + def __ne__(self, other: 'ProcessingMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5761,11 +6053,11 @@ class RecognitionJob(): :attr 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** method. - :attr list[SpeechRecognitionResults] results: (optional) If the status is + :attr 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** method. - :attr list[str] warnings: (optional) An array of warning messages about invalid + :attr 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 @@ -5774,15 +6066,15 @@ class RecognitionJob(): """ def __init__(self, - id, - status, - created, + id: str, + status: str, + created: str, *, - updated=None, - url=None, - user_token=None, - results=None, - warnings=None): + updated: str = None, + url: str = None, + user_token: str = None, + results: List['SpeechRecognitionResults'] = None, + warnings: List[str] = None) -> None: """ Initialize a RecognitionJob object. @@ -5812,11 +6104,11 @@ def __init__(self, :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** method. - :param 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** method. - :param list[str] warnings: (optional) An array of warning messages about + :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' @@ -5833,7 +6125,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} valid_keys = [ @@ -5877,7 +6169,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RecognitionJob 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: @@ -5898,17 +6195,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 RecognitionJob object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RecognitionJob') -> 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): + def __ne__(self, other: 'RecognitionJob') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5936,23 +6237,23 @@ class RecognitionJobs(): """ Information about current asynchronous speech recognition jobs. - :attr list[RecognitionJob] recognitions: An array of `RecognitionJob` objects + :attr 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): + def __init__(self, recognitions: List['RecognitionJob']) -> None: """ Initialize a RecognitionJobs object. - :param list[RecognitionJob] recognitions: An array of `RecognitionJob` + :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. """ self.recognitions = recognitions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} valid_keys = ['recognitions'] @@ -5972,24 +6273,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RecognitionJobs 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, 'recognitions') and self.recognitions is not None: _dict['recognitions'] = [x._to_dict() for x in self.recognitions] return _dict - def __str__(self): + 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 RecognitionJobs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RecognitionJobs') -> 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): + def __ne__(self, other: 'RecognitionJobs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6006,7 +6316,7 @@ class RegisterStatus(): :attr str url: The callback URL that is successfully registered. """ - def __init__(self, status, url): + def __init__(self, status: str, url: str) -> None: """ Initialize a RegisterStatus object. @@ -6020,7 +6330,7 @@ def __init__(self, status, url): self.url = url @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} valid_keys = ['status', 'url'] @@ -6042,7 +6352,12 @@ def _from_dict(cls, _dict): 'Required property \'url\' not present in RegisterStatus JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RegisterStatus 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, 'status') and self.status is not None: @@ -6051,17 +6366,21 @@ def _to_dict(self): _dict['url'] = self.url return _dict - def __str__(self): + 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 RegisterStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RegisterStatus') -> 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): + def __ne__(self, other: 'RegisterStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6097,7 +6416,8 @@ class SpeakerLabelsResult(): `false` means that the service might send further updates to the results. """ - def __init__(self, from_, to, speaker, confidence, final): + def __init__(self, from_: float, to: float, speaker: int, confidence: float, + final: bool) -> None: """ Initialize a SpeakerLabelsResult object. @@ -6125,7 +6445,7 @@ def __init__(self, from_, to, speaker, confidence, final): self.final = final @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} valid_keys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] @@ -6166,7 +6486,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerLabelsResult 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, 'from_') and self.from_ is not None: @@ -6181,17 +6506,21 @@ def _to_dict(self): _dict['final'] = self.final return _dict - def __str__(self): + 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 SpeakerLabelsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeakerLabelsResult') -> 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): + def __ne__(self, other: 'SpeakerLabelsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6211,8 +6540,9 @@ class SpeechModel(): :attr str description: A brief description of the model. """ - def __init__(self, name, language, rate, url, supported_features, - description): + def __init__(self, name: str, language: str, rate: int, url: str, + supported_features: 'SupportedFeatures', + description: str) -> None: """ Initialize a SpeechModel object. @@ -6235,7 +6565,7 @@ def __init__(self, name, language, rate, url, supported_features, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} valid_keys = [ @@ -6283,7 +6613,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechModel 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: @@ -6302,17 +6637,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 SpeechModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechModel') -> 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): + def __ne__(self, other: 'SpeechModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6321,21 +6660,21 @@ class SpeechModels(): """ Information about the available language models. - :attr list[SpeechModel] models: An array of `SpeechModel` objects that provides + :attr List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ - def __init__(self, models): + def __init__(self, models: List['SpeechModel']) -> None: """ Initialize a SpeechModels object. - :param list[SpeechModel] models: An array of `SpeechModel` objects that + :param List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -6353,24 +6692,33 @@ def _from_dict(cls, _dict): 'Required property \'models\' not present in SpeechModels JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechModels 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 SpeechModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechModels') -> 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): + def __ne__(self, other: 'SpeechModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6383,12 +6731,12 @@ class SpeechRecognitionAlternative(): :attr float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. - :attr list[str] timestamps: (optional) Time alignments for each word from the + :attr 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 + :attr 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.866]]`. Confidence scores are returned only for the @@ -6396,11 +6744,11 @@ class SpeechRecognitionAlternative(): """ def __init__(self, - transcript, + transcript: str, *, - confidence=None, - timestamps=None, - word_confidence=None): + confidence: float = None, + timestamps: List[str] = None, + word_confidence: List[str] = None) -> None: """ Initialize a SpeechRecognitionAlternative object. @@ -6409,12 +6757,12 @@ def __init__(self, confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. - :param list[str] timestamps: (optional) Time alignments for each word from + :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. - :param list[str] word_confidence: (optional) A confidence score for each + :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.866]]`. Confidence scores are returned @@ -6426,7 +6774,7 @@ def __init__(self, self.word_confidence = word_confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} valid_keys = [ @@ -6451,7 +6799,12 @@ def _from_dict(cls, _dict): args['word_confidence'] = _dict.get('word_confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionAlternative 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, 'transcript') and self.transcript is not None: @@ -6465,17 +6818,21 @@ def _to_dict(self): _dict['word_confidence'] = self.word_confidence return _dict - def __str__(self): + 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 SpeechRecognitionAlternative object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionAlternative') -> 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): + def __ne__(self, other: 'SpeechRecognitionAlternative') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6487,7 +6844,7 @@ class SpeechRecognitionResult(): :attr bool final: An indication of whether the transcription results are final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. - :attr list[SpeechRecognitionAlternative] alternatives: An array of alternative + :attr 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 @@ -6497,17 +6854,28 @@ class SpeechRecognitionResult(): `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 + :attr 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` + 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 + grammatical sentence. The insertion of splits is influenced by the base language + model and biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds the + two-minute maximum. The service splits the transcript to avoid excessive memory + use. + * `silence` - A pause or silence that is at least as long as the pause interval. """ def __init__(self, - final, - alternatives, + final: bool, + alternatives: List['SpeechRecognitionAlternative'], *, - keywords_result=None, - word_alternatives=None): + keywords_result: dict = None, + word_alternatives: List['WordAlternativeResults'] = None, + end_of_utterance: str = None) -> None: """ Initialize a SpeechRecognitionResult object. @@ -6515,7 +6883,7 @@ def __init__(self, final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. - :param list[SpeechRecognitionAlternative] alternatives: An array of + :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. :param dict keywords_result: (optional) A dictionary (or associative array) @@ -6525,21 +6893,35 @@ def __init__(self, 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. - :param list[WordAlternativeResults] word_alternatives: (optional) An array + :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. + :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 + grammatical sentence. The insertion of splits is influenced by the base + language model and biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds + the two-minute maximum. The service splits the transcript to avoid + excessive memory use. + * `silence` - A pause or silence that is at least as long as the pause + interval. """ self.final = final self.alternatives = alternatives self.keywords_result = keywords_result self.word_alternatives = word_alternatives + self.end_of_utterance = end_of_utterance @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} valid_keys = [ - 'final', 'alternatives', 'keywords_result', 'word_alternatives' + 'final', 'alternatives', 'keywords_result', 'word_alternatives', + 'end_of_utterance' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -6568,9 +6950,16 @@ def _from_dict(cls, _dict): WordAlternativeResults._from_dict(x) for x in (_dict.get('word_alternatives')) ] + if 'end_of_utterance' in _dict: + args['end_of_utterance'] = _dict.get('end_of_utterance') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionResult 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, 'final') and self.final is not None: @@ -6585,28 +6974,53 @@ def _to_dict(self): _dict['word_alternatives'] = [ x._to_dict() for x in self.word_alternatives ] + if hasattr(self, + 'end_of_utterance') and self.end_of_utterance is not None: + _dict['end_of_utterance'] = self.end_of_utterance return _dict - def __str__(self): + 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 SpeechRecognitionResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionResult') -> 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): + def __ne__(self, other: 'SpeechRecognitionResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class EndOfUtteranceEnum(Enum): + """ + 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 grammatical + sentence. The insertion of splits is influenced by the base language model and + biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds the + two-minute maximum. The service splits the transcript to avoid excessive memory + 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(): """ The complete results for a speech recognition request. - :attr list[SpeechRecognitionResult] results: (optional) An array of + :attr 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 @@ -6616,7 +7030,7 @@ class SpeechRecognitionResults(): :attr int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. - :attr list[SpeakerLabelsResult] speaker_labels: (optional) An array of + :attr 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 @@ -6628,7 +7042,7 @@ class SpeechRecognitionResults(): method. :attr 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 + :attr 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 @@ -6646,16 +7060,16 @@ class SpeechRecognitionResults(): def __init__(self, *, - results=None, - result_index=None, - speaker_labels=None, - processing_metrics=None, - audio_metrics=None, - warnings=None): + 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: """ Initialize a SpeechRecognitionResults object. - :param 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 @@ -6666,7 +7080,7 @@ def __init__(self, :param int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. - :param list[SpeakerLabelsResult] speaker_labels: (optional) An array of + :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 @@ -6679,7 +7093,7 @@ def __init__(self, **Recognize audio** method. :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :param list[str] warnings: (optional) An array of warning messages + :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 @@ -6702,7 +7116,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} valid_keys = [ @@ -6736,7 +7150,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionResults 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, 'results') and self.results is not None: @@ -6757,17 +7176,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 SpeechRecognitionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionResults') -> 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): + def __ne__(self, other: 'SpeechRecognitionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6782,7 +7205,8 @@ class SupportedFeatures(): be used with the language model. """ - def __init__(self, custom_language_model, speaker_labels): + def __init__(self, custom_language_model: bool, + speaker_labels: bool) -> None: """ Initialize a SupportedFeatures object. @@ -6796,7 +7220,7 @@ def __init__(self, custom_language_model, speaker_labels): self.speaker_labels = speaker_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} valid_keys = ['custom_language_model', 'speaker_labels'] @@ -6819,7 +7243,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SupportedFeatures 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, 'custom_language_model' @@ -6829,17 +7258,21 @@ def _to_dict(self): _dict['speaker_labels'] = self.speaker_labels return _dict - def __str__(self): + 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 SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SupportedFeatures') -> 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): + def __ne__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6848,18 +7281,18 @@ class TrainingResponse(): """ The response from training of a custom language or custom acoustic model. - :attr list[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + :attr 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=None): + def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: """ Initialize a TrainingResponse object. - :param list[TrainingWarning] warnings: (optional) An array of + :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 @@ -6868,7 +7301,7 @@ def __init__(self, *, warnings=None): self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} valid_keys = ['warnings'] @@ -6883,24 +7316,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingResponse 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, 'warnings') and self.warnings is not None: _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 TrainingResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingResponse') -> 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): + def __ne__(self, other: 'TrainingResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6918,7 +7360,7 @@ class TrainingWarning(): training.`. """ - def __init__(self, code, message): + def __init__(self, code: str, message: str) -> None: """ Initialize a TrainingWarning object. @@ -6934,7 +7376,7 @@ def __init__(self, code, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} valid_keys = ['code', 'message'] @@ -6957,7 +7399,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingWarning 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, 'code') and self.code is not None: @@ -6966,17 +7413,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 TrainingWarning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingWarning') -> 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): + def __ne__(self, other: 'TrainingWarning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6996,7 +7447,7 @@ class Word(): :attr 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 pronunciations for the word. The array + :attr List[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. @@ -7010,30 +7461,30 @@ class Word(): it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. - :attr list[str] source: An array of sources that describes how the word was + :attr List[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. - :attr list[WordError] error: (optional) If the service discovered one or more + :attr 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, - sounds_like, - display_as, - count, - source, + word: str, + sounds_like: List[str], + display_as: str, + count: int, + source: List[str], *, - error=None): + error: List['WordError'] = None) -> None: """ Initialize a Word object. :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param list[str] sounds_like: An array of pronunciations for the word. The + :param List[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. @@ -7047,12 +7498,12 @@ def __init__(self, before it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. - :param list[str] source: An array of sources that describes how the word + :param List[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. - :param list[WordError] error: (optional) If the service discovered one or + :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. """ @@ -7064,7 +7515,7 @@ def __init__(self, self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} valid_keys = [ @@ -7106,7 +7557,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Word 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, 'word') and self.word is not None: @@ -7123,17 +7579,21 @@ def _to_dict(self): _dict['error'] = [x._to_dict() for x in self.error] return _dict - def __str__(self): + 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 Word object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Word') -> 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): + def __ne__(self, other: 'Word') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7147,7 +7607,7 @@ class WordAlternativeResult(): :attr str word: An alternative hypothesis for a word from the input audio. """ - def __init__(self, confidence, word): + def __init__(self, confidence: float, word: str) -> None: """ Initialize a WordAlternativeResult object. @@ -7159,7 +7619,7 @@ def __init__(self, confidence, word): self.word = word @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} valid_keys = ['confidence', 'word'] @@ -7182,7 +7642,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordAlternativeResult 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, 'confidence') and self.confidence is not None: @@ -7191,17 +7656,21 @@ def _to_dict(self): _dict['word'] = self.word return _dict - def __str__(self): + 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 WordAlternativeResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordAlternativeResult') -> 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): + def __ne__(self, other: 'WordAlternativeResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7214,11 +7683,12 @@ class WordAlternativeResults(): audio that corresponds to the word alternatives. :attr 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 + :attr List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ - def __init__(self, start_time, end_time, alternatives): + def __init__(self, start_time: float, end_time: float, + alternatives: List['WordAlternativeResult']) -> None: """ Initialize a WordAlternativeResults object. @@ -7226,7 +7696,7 @@ def __init__(self, start_time, end_time, alternatives): input audio that corresponds to the word alternatives. :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :param list[WordAlternativeResult] alternatives: An array of alternative + :param List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ self.start_time = start_time @@ -7234,7 +7704,7 @@ def __init__(self, start_time, end_time, alternatives): self.alternatives = alternatives @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} valid_keys = ['start_time', 'end_time', 'alternatives'] @@ -7266,7 +7736,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordAlternativeResults 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, 'start_time') and self.start_time is not None: @@ -7277,17 +7752,21 @@ def _to_dict(self): _dict['alternatives'] = [x._to_dict() for x in self.alternatives] return _dict - def __str__(self): + 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 WordAlternativeResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordAlternativeResults') -> 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): + def __ne__(self, other: 'WordAlternativeResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7305,7 +7784,7 @@ class WordError(): '{suggested_string}'."`. """ - def __init__(self, element): + def __init__(self, element: str) -> None: """ Initialize a WordError object. @@ -7320,7 +7799,7 @@ def __init__(self, element): self.element = element @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} valid_keys = ['element'] @@ -7336,24 +7815,33 @@ def _from_dict(cls, _dict): 'Required property \'element\' not present in WordError JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordError 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, 'element') and self.element is not None: _dict['element'] = self.element return _dict - def __str__(self): + 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 WordError object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordError') -> 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): + def __ne__(self, other: 'WordError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7362,23 +7850,23 @@ class Words(): """ Information about the words from a custom language model. - :attr list[Word] words: An array of `Word` objects that provides information + :attr 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): + def __init__(self, words: List['Word']) -> None: """ Initialize a Words object. - :param list[Word] words: An array of `Word` objects that provides + :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. """ self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} valid_keys = ['words'] @@ -7394,23 +7882,32 @@ def _from_dict(cls, _dict): 'Required property \'words\' not present in Words JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Words 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, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 Words object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Words') -> 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): + def __ne__(self, other: 'Words') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index dd02220d8..c3a534087 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,592 +1,3120 @@ -# coding=utf-8 -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import ibm_watson -from ibm_watson.speech_to_text_v1 import CustomWord -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -def test_success(): - models_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models' - models_response = '{"models": [{"url": "https://stream.watsonplatform.net/speech-to-text/api/v1/models/' \ - 'WatsonModel", "rate": 16000, "name": "WatsonModel", "language": "en-US", "description": ' \ - '"Watson model \'v7w_134k.3\' for Attila 2-5 reco engine."}]}' - - responses.add( - responses.GET, - models_url, - body=models_response, - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.list_models() - - assert responses.calls[0].request.url == models_url - assert responses.calls[0].response.text == models_response - - recognize_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize' - recognize_response = '{"results":[{"alternatives":[{"transcript":"thunderstorms could produce large hail ' \ - 'isolated tornadoes and heavy rain "}],"final":true}],"result_index":0}' - - responses.add( - responses.POST, - recognize_url, - body=recognize_response, - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.recognize( - audio=audio_file, content_type='audio/l16; rate=44100') - - request_url = responses.calls[1].request.url - assert request_url == recognize_url - assert responses.calls[1].response.text == recognize_response - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.recognize( - audio=audio_file, customization_id='x', content_type='audio/l16; rate=44100') - expected_url = "{0}?customization_id=x".format(recognize_url) - assert expected_url == responses.calls[2].request.url - assert len(responses.calls) == 3 - - -@responses.activate -def test_get_model(): - model_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models/modelid' - responses.add( - responses.GET, - model_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.get_model(model_id='modelid') - assert len(responses.calls) == 1 - - -def _decode_body(body): +import tempfile +import ibm_watson.speech_to_text_v1 +from ibm_watson.speech_to_text_v1 import * + +base_url = 'https://stream.watsonplatform.net/speech-to-text/api' + +############################################################################## +# Start of Service: Models +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_SpeechModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_model +#----------------------------------------------------------------------------- +class TestGetModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_response(self): + body = self.construct_full_body() + response = fake_response_SpeechModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_empty(self): + check_empty_required_params(self, fake_response_SpeechModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models/{0}'.format(body['model_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Models +############################################################################## + +############################################################################## +# Start of Service: Synchronous +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for recognize +#----------------------------------------------------------------------------- +class TestRecognize(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_recognize_response(self): + body = self.construct_full_body() + response = fake_response_SpeechRecognitionResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_recognize_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechRecognitionResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_recognize_empty(self): + check_empty_required_params( + self, fake_response_SpeechRecognitionResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognize' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.recognize(**body) + return output + + def construct_full_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['model'] = "string1" + body['language_customization_id'] = "string1" + body['acoustic_customization_id'] = "string1" + body['base_model_version'] = "string1" + body['customization_weight'] = 12345.0 + body['inactivity_timeout'] = 12345 + body['keywords'] = [] + body['keywords_threshold'] = 12345.0 + body['max_alternatives'] = 12345 + body['word_alternatives_threshold'] = 12345.0 + body['word_confidence'] = True + body['timestamps'] = True + body['profanity_filter'] = True + body['smart_formatting'] = True + body['speaker_labels'] = True + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['redaction'] = True + body['audio_metrics'] = True + body['end_of_phrase_silence_time'] = 12345.0 + body['split_transcript_at_phrase_end'] = True + return body + + def construct_required_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Synchronous +############################################################################## + +############################################################################## +# Start of Service: Asynchronous +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for register_callback +#----------------------------------------------------------------------------- +class TestRegisterCallback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_register_callback_response(self): + body = self.construct_full_body() + response = fake_response_RegisterStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_register_callback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RegisterStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_register_callback_empty(self): + check_empty_required_params(self, fake_response_RegisterStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/register_callback' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.register_callback(**body) + return output + + def construct_full_body(self): + body = dict() + body['callback_url'] = "string1" + body['user_secret'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for unregister_callback +#----------------------------------------------------------------------------- +class TestUnregisterCallback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_unregister_callback_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_unregister_callback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_unregister_callback_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/unregister_callback' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.unregister_callback(**body) + return output + + def construct_full_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_job +#----------------------------------------------------------------------------- +class TestCreateJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_job_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_job_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_job_empty(self): + check_empty_required_params(self, fake_response_RecognitionJob_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['model'] = "string1" + body['callback_url'] = "string1" + body['events'] = "string1" + body['user_token'] = "string1" + body['results_ttl'] = 12345 + body['language_customization_id'] = "string1" + body['acoustic_customization_id'] = "string1" + body['base_model_version'] = "string1" + body['customization_weight'] = 12345.0 + body['inactivity_timeout'] = 12345 + body['keywords'] = [] + body['keywords_threshold'] = 12345.0 + body['max_alternatives'] = 12345 + body['word_alternatives_threshold'] = 12345.0 + body['word_confidence'] = True + body['timestamps'] = True + body['profanity_filter'] = True + body['smart_formatting'] = True + body['speaker_labels'] = True + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['redaction'] = True + body['processing_metrics'] = True + body['processing_metrics_interval'] = 12345.0 + body['audio_metrics'] = True + body['end_of_phrase_silence_time'] = 12345.0 + body['split_transcript_at_phrase_end'] = True + return body + + def construct_required_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for check_jobs +#----------------------------------------------------------------------------- +class TestCheckJobs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_jobs_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJobs_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_jobs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJobs_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_jobs_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.check_jobs(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for check_job +#----------------------------------------------------------------------------- +class TestCheckJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_job_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_job_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_job_empty(self): + check_empty_required_params(self, fake_response_RecognitionJob_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions/{0}'.format(body['id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.check_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_job +#----------------------------------------------------------------------------- +class TestDeleteJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_job_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_job_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_job_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions/{0}'.format(body['id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Asynchronous +############################################################################## + +############################################################################## +# Start of Service: CustomLanguageModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_language_model +#----------------------------------------------------------------------------- +class TestCreateLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_language_model_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_language_model_empty(self): + check_empty_required_params(self, fake_response_LanguageModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "dialect": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "dialect": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_language_models +#----------------------------------------------------------------------------- +class TestListLanguageModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_language_models_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_language_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_language_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_language_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_language_model +#----------------------------------------------------------------------------- +class TestGetLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_language_model_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_language_model_empty(self): + check_empty_required_params(self, fake_response_LanguageModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_language_model +#----------------------------------------------------------------------------- +class TestDeleteLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_language_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_language_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for train_language_model +#----------------------------------------------------------------------------- +class TestTrainLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_language_model_response(self): + body = self.construct_full_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_language_model_empty(self): + check_empty_required_params(self, fake_response_TrainingResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/train'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.train_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_type_to_add'] = "string1" + body['customization_weight'] = 12345.0 + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for reset_language_model +#----------------------------------------------------------------------------- +class TestResetLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_language_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_language_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/reset'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.reset_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for upgrade_language_model +#----------------------------------------------------------------------------- +class TestUpgradeLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_language_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_language_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/upgrade_model'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.upgrade_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomLanguageModels +############################################################################## + +############################################################################## +# Start of Service: CustomCorpora +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_corpora +#----------------------------------------------------------------------------- +class TestListCorpora(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_corpora_response(self): + body = self.construct_full_body() + response = fake_response_Corpora_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_corpora_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Corpora_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_corpora_empty(self): + check_empty_required_params(self, fake_response_Corpora_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_corpora(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_corpus +#----------------------------------------------------------------------------- +class TestAddCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_corpus_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_corpus_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_corpus_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + body['corpus_file'] = tempfile.NamedTemporaryFile() + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + body['corpus_file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_corpus +#----------------------------------------------------------------------------- +class TestGetCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_corpus_response(self): + body = self.construct_full_body() + response = fake_response_Corpus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_corpus_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Corpus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_corpus_empty(self): + check_empty_required_params(self, fake_response_Corpus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_corpus +#----------------------------------------------------------------------------- +class TestDeleteCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_corpus_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_corpus_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_corpus_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomCorpora +############################################################################## + +############################################################################## +# Start of Service: CustomWords +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_words +#----------------------------------------------------------------------------- +class TestListWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_response(self): + body = self.construct_full_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_empty(self): + check_empty_required_params(self, fake_response_Words_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_type'] = "string1" + body['sort'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_words +#----------------------------------------------------------------------------- +class TestAddWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_word +#----------------------------------------------------------------------------- +class TestAddWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + body.update({ + "word": "string1", + "sounds_like": [], + "display_as": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + body.update({ + "word": "string1", + "sounds_like": [], + "display_as": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_word +#----------------------------------------------------------------------------- +class TestGetWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_response(self): + body = self.construct_full_body() + response = fake_response_Word_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Word_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_empty(self): + check_empty_required_params(self, fake_response_Word_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_word +#----------------------------------------------------------------------------- +class TestDeleteWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomWords +############################################################################## + +############################################################################## +# Start of Service: CustomGrammars +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_grammars +#----------------------------------------------------------------------------- +class TestListGrammars(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_grammars_response(self): + body = self.construct_full_body() + response = fake_response_Grammars_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_grammars_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Grammars_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_grammars_empty(self): + check_empty_required_params(self, fake_response_Grammars_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_grammars(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_grammar +#----------------------------------------------------------------------------- +class TestAddGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_grammar_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_grammar_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_grammar_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['grammar_file'] = "string1" + body['content_type'] = "string1" + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['grammar_file'] = "string1" + body['content_type'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_grammar +#----------------------------------------------------------------------------- +class TestGetGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_grammar_response(self): + body = self.construct_full_body() + response = fake_response_Grammar_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_grammar_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Grammar_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_grammar_empty(self): + check_empty_required_params(self, fake_response_Grammar_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_grammar +#----------------------------------------------------------------------------- +class TestDeleteGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_grammar_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_grammar_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_grammar_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomGrammars +############################################################################## + +############################################################################## +# Start of Service: CustomAcousticModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_acoustic_model +#----------------------------------------------------------------------------- +class TestCreateAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_AcousticModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_acoustic_models +#----------------------------------------------------------------------------- +class TestListAcousticModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_acoustic_models_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_acoustic_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_acoustic_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_acoustic_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_acoustic_model +#----------------------------------------------------------------------------- +class TestGetAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_AcousticModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_acoustic_model +#----------------------------------------------------------------------------- +class TestDeleteAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_acoustic_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for train_acoustic_model +#----------------------------------------------------------------------------- +class TestTrainAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_TrainingResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/train'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.train_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['custom_language_model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for reset_acoustic_model +#----------------------------------------------------------------------------- +class TestResetAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_acoustic_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/reset'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.reset_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for upgrade_acoustic_model +#----------------------------------------------------------------------------- +class TestUpgradeAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_acoustic_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/upgrade_model'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.upgrade_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['custom_language_model_id'] = "string1" + body['force'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomAcousticModels +############################################################################## + +############################################################################## +# Start of Service: CustomAudioResources +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_audio +#----------------------------------------------------------------------------- +class TestListAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_audio_response(self): + body = self.construct_full_body() + response = fake_response_AudioResources_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AudioResources_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_audio_empty(self): + check_empty_required_params(self, fake_response_AudioResources_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_audio +#----------------------------------------------------------------------------- +class TestAddAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_audio_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_audio_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + body['audio_resource'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['contained_content_type'] = "string1" + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + body['audio_resource'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_audio +#----------------------------------------------------------------------------- +class TestGetAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_audio_response(self): + body = self.construct_full_body() + response = fake_response_AudioListing_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AudioListing_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_audio_empty(self): + check_empty_required_params(self, fake_response_AudioListing_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_audio +#----------------------------------------------------------------------------- +class TestDeleteAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_audio_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_audio_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomAudioResources +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False try: - return body.decode('utf-8') - except: - return body - - -@responses.activate -def test_recognitions(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognitions' - get_response = '{"recognitions": [{"created": "2018-02-01T17:43:15.432Z","id": "6193190c-0777-11e8-9b4b-43ad845196dd","updated": "2018-02-01T17:43:17.998Z","status": "failed"}]}' - responses.add( - responses.GET, - url, - body=get_response, - status=200, - content_type='application/json') - - responses.add( - responses.POST, - url, - body='{"status": "waiting"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/jobid".format(url), - body='{"description": "deleted successfully"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/jobid".format(url), - body='{"status": "waiting"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.check_jobs() - assert responses.calls[0].response.json()['recognitions'][0][ - 'id'] == '6193190c-0777-11e8-9b4b-43ad845196dd' - - speech_to_text.check_job('jobid') - assert responses.calls[1].response.json() == {'status': 'waiting'} - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.create_job(audio=audio_file, content_type='audio/basic') - assert responses.calls[2].response.json() == {'status': 'waiting'} - - speech_to_text.delete_job('jobid') - assert responses.calls[3].response.json() == { - "description": "deleted successfully" - } - - assert len(responses.calls) == 4 - - -@responses.activate -def test_callbacks(): - base_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1' - responses.add( - responses.POST, - "{0}/register_callback".format(base_url), - body='{"status": "created", "url": "monitorcalls.com"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}/unregister_callback".format(base_url), - body='{"response": "The callback URL was successfully unregistered"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.register_callback("monitorcalls.com") - assert responses.calls[0].response.json() == { - "status": "created", - "url": "monitorcalls.com" - } - - speech_to_text.unregister_callback("monitorcalls.com") - assert responses.calls[1].response.json() == { - "response": "The callback URL was successfully unregistered" - } - - assert len(responses.calls) == 2 - - -@responses.activate -def test_custom_model(): - customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations' - train_url = "{0}/{1}/train".format(customization_url, 'customid') - - responses.add( - responses.GET, - customization_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - customization_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/modelid".format(customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/modelid".format(customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - train_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_language_models() - - speech_to_text.create_language_model( - name="Example model", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[1].request.body)) - assert parsed_body['name'] == 'Example model' - - speech_to_text.create_language_model( - name="Example model Two", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[2].request.body)) - assert parsed_body['name'] == 'Example model Two' - assert parsed_body['base_model_name'] == 'en-US_BroadbandModel' - - speech_to_text.train_language_model('customid') - speech_to_text.get_language_model(customization_id='modelid') - speech_to_text.delete_language_model(customization_id='modelid') - - assert len(responses.calls) == 6 - - -@responses.activate -def test_acoustic_model(): - acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations' - train_url = "{0}/{1}/train".format(acoustic_customization_url, 'customid') - - responses.add( - responses.GET, - acoustic_customization_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - acoustic_customization_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/modelid".format(acoustic_customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/modelid".format(acoustic_customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - train_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_acoustic_models() - - speech_to_text.create_acoustic_model( - name="Example model", - base_model_name="en-US_BroadbandModel", - description="Example custom language model") - - parsed_body = json.loads(_decode_body(responses.calls[1].request.body)) - assert parsed_body['name'] == 'Example model' - - speech_to_text.create_acoustic_model( - name="Example model Two", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[2].request.body)) - assert parsed_body['name'] == 'Example model Two' - assert parsed_body['base_model_name'] == 'en-US_BroadbandModel' - - speech_to_text.train_acoustic_model('customid') - speech_to_text.get_acoustic_model(customization_id='modelid') - speech_to_text.delete_acoustic_model(customization_id='modelid') - - assert len(responses.calls) == 6 - -@responses.activate -def test_upgrade_acoustic_model(): - acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations' - upgrade_url = "{0}/{1}/upgrade_model".format(acoustic_customization_url, 'customid') - - responses.add( - responses.POST, - upgrade_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.upgrade_acoustic_model( - 'customid', - custom_language_model_id='model_x', - force=True) - assert responses.calls[0].response.json() == {"bogus_response": "yep"} - - assert len(responses.calls) == 1 - - -def test_custom_corpora(): - - corpora_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/corpora' - get_corpora_url = '{0}/{1}'.format( - corpora_url.format('customid'), 'corpus') - - with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps: - rsps.add( - responses.GET, - corpora_url.format('customid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.POST, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.GET, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.DELETE, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_corpora(customization_id='customid') - - file_path = '../../resources/speech_to_text/corpus-short-1.txt' - full_path = os.path.join(os.path.dirname(__file__), file_path) - with open(full_path) as corpus_file: - speech_to_text.add_corpus( - customization_id='customid', - corpus_name="corpus", - corpus_file=corpus_file) - - speech_to_text.get_corpus( - customization_id='customid', corpus_name='corpus') - - speech_to_text.delete_corpus( - customization_id='customid', corpus_name='corpus') - - -@responses.activate -def test_custom_words(): - words_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words' - word_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words/{1}' - - responses.add( - responses.PUT, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.PUT, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - words_url.format('custid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - words_url.format('custid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - custom_word = CustomWord( - word="IEEE", sounds_like=["i triple e"], display_as="IEEE") - - speech_to_text.add_word( - customization_id='custid', - word_name="IEEE", - sounds_like=["i triple e"], - display_as="IEEE") - - speech_to_text.delete_word(customization_id='custid', word_name="wordname") - - speech_to_text.delete_word(customization_id='custid', word_name='IEEE') - - custom_words = [custom_word, custom_word, custom_word] - speech_to_text.add_words( - customization_id='custid', - words=custom_words) - - speech_to_text.get_word(customization_id='custid', word_name="IEEE") - - speech_to_text.get_word(customization_id='custid', word_name='wordname') - - speech_to_text.list_words(customization_id='custid') - speech_to_text.list_words(customization_id='custid', sort='alphabetical') - - speech_to_text.list_words(customization_id='custid', word_type='all') - - assert len(responses.calls) == 9 - - -@responses.activate -def test_custom_audio_resources(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/{0}/audio/{1}' - - responses.add( - responses.POST, - url.format('custid', 'hiee'), - body='{"post response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - url.format('custid', 'hiee'), - body='{"delete response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url.format('custid', 'hiee'), - body='{"get response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/custid/audio', - body='{"get response all": "done"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.add_audio( - customization_id='custid', - audio_name="hiee", - audio_resource=audio_file, - content_type="application/json") - assert responses.calls[0].response.json() == {"post response": "done"} - - speech_to_text.delete_audio('custid', 'hiee') - assert responses.calls[1].response.json() == {"delete response": "done"} - - speech_to_text.get_audio('custid', 'hiee') - assert responses.calls[2].response.json() == {"get response": "done"} - - speech_to_text.list_audio('custid') - assert responses.calls[3].response.json() == {"get response all": "done"} - -@responses.activate -def test_delete_user_data(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - response = speech_to_text.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - -@responses.activate -def test_custom_grammars(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/grammars/{1}' - - responses.add( - responses.POST, - url.format('customization_id', 'grammar_name'), - body='{}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - url.format('customization_id', 'grammar_name'), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url.format('customization_id', 'grammar_name'), - body='{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url='https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/customization_id/grammars', - body='{"grammars":[{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}]}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/confirm-grammar.xml'), 'rb') as grammar_file: - speech_to_text.add_grammar( - "customization_id", - grammar_name='grammar_name', - grammar_file=grammar_file, - content_type='application/srgs+xml', - allow_overwrite=True) - assert responses.calls[0].response.json() == {} - - speech_to_text.delete_grammar('customization_id', 'grammar_name') - assert responses.calls[1].response.status_code == 200 - - speech_to_text.get_grammar('customization_id', 'grammar_name') - assert responses.calls[2].response.json() == {"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0} - - speech_to_text.list_grammars('customization_id') - assert responses.calls[3].response.json() == {"grammars":[{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}]} + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_SpeechModels_json = """{"models": []}""" +fake_response_SpeechModel_json = """{"name": "fake_name", "language": "fake_language", "rate": 4, "url": "fake_url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "fake_description"}""" +fake_response_SpeechRecognitionResults_json = """{"results": [], "result_index": 12, "speaker_labels": [], "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": [], "clipping_rate": [], "speech_level": [], "non_speech_level": []}}, "warnings": []}""" +fake_response_RegisterStatus_json = """{"status": "fake_status", "url": "fake_url"}""" +fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" +fake_response_RecognitionJobs_json = """{"recognitions": []}""" +fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" +fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" +fake_response_LanguageModels_json = """{"customizations": []}""" +fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" +fake_response_TrainingResponse_json = """{"warnings": []}""" +fake_response_Corpora_json = """{"corpora": []}""" +fake_response_Corpus_json = """{"name": "fake_name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" +fake_response_Words_json = """{"words": []}""" +fake_response_Word_json = """{"word": "fake_word", "sounds_like": [], "display_as": "fake_display_as", "count": 5, "source": [], "error": []}""" +fake_response_Grammars_json = """{"grammars": []}""" +fake_response_Grammar_json = """{"name": "fake_name", "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" +fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" +fake_response_AcousticModels_json = """{"customizations": []}""" +fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" +fake_response_TrainingResponse_json = """{"warnings": []}""" +fake_response_AudioResources_json = """{"total_minutes_of_audio": 22, "audio": []}""" +fake_response_AudioListing_json = """{"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status", "container": {"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status"}, "audio": []}""" From 040946f88d6b652f8b8e5638429b69fb1035e79a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:04:26 -0500 Subject: [PATCH 19/28] feat(stt): New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket --- ibm_watson/speech_to_text_v1_adapter.py | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 9f59e4721..c813b5370 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -51,6 +51,8 @@ def recognize_using_websocket(self, processing_metrics=None, processing_metrics_interval=None, audio_metrics=None, + end_of_phrase_silence_time=None, + split_transcript_at_phrase_end=None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -188,6 +190,31 @@ def recognize_using_websocket(self, :param bool audio_metrics: If `true`, requests detailed information about the signal characteristics of the input audio. The service returns audio metrics with the final transcription results. By default, the service returns no audio metrics. + :param float end_of_phrase_silence_time: (optional) If `true`, specifies + the duration of the pause interval at which the service splits a transcript + into multiple final results. If the service detects pauses or extended + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + The default pause interval for most languages is 0.8 seconds; the default + for Chinese is 0.6 seconds. + See [End of phrase silence + time](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#silence_time). + :param bool split_transcript_at_phrase_end: (optional) If `true`, directs + the service to split the transcript into multiple final results based on + semantic features of the input, for example, at the conclusion of + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + where the service splits a transcript. By default, the service splits + transcripts based solely on the pause interval. + See [Split transcript at phrase + end](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#split_transcript). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict From aa8fe87da8554daeefd2611e7e9f6e007fbff45c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:05:27 -0500 Subject: [PATCH 20/28] refactor(tts): regenerate text to speech with tests --- ibm_watson/text_to_speech_v1.py | 499 +++++---- test/unit/test_text_to_speech_v1.py | 1470 ++++++++++++++++++++++----- 2 files changed, 1530 insertions(+), 439 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 2b8084043..371bdf07f 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. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -31,11 +31,16 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import Dict +from typing import List ############################################################################## # Service @@ -45,12 +50,14 @@ class TextToSpeechV1(BaseService): """The Text to Speech V1 service.""" - default_service_url = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_NAME = 'text_to_speech' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Text to Speech service. @@ -58,29 +65,19 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('text_to_speech') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('text_to_speech') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Voices ######################### - def list_voices(self, **kwargs): + def list_voices(self, **kwargs) -> 'DetailedResponse': """ List voices. @@ -98,18 +95,19 @@ def list_voices(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'list_voices') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voices') headers.update(sdk_headers) url = '/v1/voices' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_voice(self, voice, *, customization_id=None, **kwargs): + def get_voice(self, voice: str, *, customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Get a voice. @@ -138,7 +136,9 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', '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 = {'customization_id': customization_id} @@ -147,8 +147,8 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -157,12 +157,12 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): ######################### def synthesize(self, - text, + text: str, *, - accept=None, - voice=None, - customization_id=None, - **kwargs): + accept: str = None, + voice: str = None, + customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Synthesize audio. @@ -248,7 +248,9 @@ def synthesize(self, headers = {'Accept': accept} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'synthesize') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='synthesize') headers.update(sdk_headers) params = {'voice': voice, 'customization_id': customization_id} @@ -260,8 +262,8 @@ def synthesize(self, url=url, headers=headers, params=params, - data=data, - accept_json=False) + data=data) + response = self.send(request) return response @@ -270,12 +272,12 @@ def synthesize(self, ######################### def get_pronunciation(self, - text, + text: str, *, - voice=None, - format=None, - customization_id=None, - **kwargs): + voice: str = None, + format: str = None, + customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Get pronunciation. @@ -283,7 +285,8 @@ 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 voice model to see the translation for that voice model. - **Note:** This method is currently a beta release. + **Note:** This method is currently a beta release. The method does not support the + Arabic, Chinese, and Dutch languages. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -313,8 +316,9 @@ def get_pronunciation(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - '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 = { @@ -328,8 +332,8 @@ def get_pronunciation(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -338,11 +342,11 @@ def get_pronunciation(self, ######################### def create_voice_model(self, - name, + name: str, *, - language=None, - description=None, - **kwargs): + language: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom model. @@ -350,7 +354,8 @@ def create_voice_model(self, model. You can optionally specify the language and a description for the new model. The model is owned by the instance of the service whose credentials are used to create it. - **Note:** This method is currently a beta release. + **Note:** This method is currently a beta release. The service does not support + voice model customization for the Arabic, Chinese, and Dutch languages. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). @@ -370,8 +375,9 @@ def create_voice_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'create_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_voice_model') headers.update(sdk_headers) data = {'name': name, 'language': language, 'description': description} @@ -380,12 +386,13 @@ def create_voice_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_voice_models(self, *, language=None, **kwargs): + def list_voice_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom models. @@ -410,8 +417,9 @@ def list_voice_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'list_voice_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voice_models') headers.update(sdk_headers) params = {'language': language} @@ -420,18 +428,18 @@ def list_voice_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_voice_model(self, - customization_id, + customization_id: str, *, - name=None, - description=None, - words=None, - **kwargs): + name: str = None, + description: str = None, + words: List['Word'] = None, + **kwargs) -> 'DetailedResponse': """ Update a custom model. @@ -466,7 +474,7 @@ def update_voice_model(self, :param str name: (optional) A new name for the custom voice model. :param str description: (optional) A new description for the custom voice model. - :param list[Word] words: (optional) An array of `Word` objects that + :param List[Word] words: (optional) An array of `Word` objects that provides the words and their translations that are to be added or updated for the custom voice model. Pass an empty array to make no additions or updates. @@ -483,8 +491,9 @@ def update_voice_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'update_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_voice_model') headers.update(sdk_headers) data = {'name': name, 'description': description, 'words': words} @@ -494,12 +503,13 @@ def update_voice_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_voice_model(self, customization_id, **kwargs): + def get_voice_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom model. @@ -525,19 +535,20 @@ def get_voice_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'get_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_voice_model(self, customization_id, **kwargs): + def delete_voice_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom model. @@ -561,16 +572,17 @@ def delete_voice_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'delete_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_voice_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -578,7 +590,8 @@ def delete_voice_model(self, customization_id, **kwargs): # Custom words ######################### - def add_words(self, customization_id, words, **kwargs): + def add_words(self, customization_id: str, words: List['Word'], + **kwargs) -> 'DetailedResponse': """ Add custom words. @@ -609,7 +622,7 @@ def add_words(self, customization_id, words, **kwargs): :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of the service that owns the custom model. - :param list[Word] words: The **Add custom words** method accepts an array + :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each @@ -631,7 +644,9 @@ def add_words(self, customization_id, words, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', '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 = {'words': words} @@ -641,12 +656,12 @@ def add_words(self, customization_id, words, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_words(self, customization_id, **kwargs): + def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': """ List custom words. @@ -672,25 +687,25 @@ def list_words(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'list_words') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words') headers.update(sdk_headers) url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_word(self, - customization_id, - word, - translation, + customization_id: str, + word: str, + translation: str, *, - part_of_speech=None, - **kwargs): + part_of_speech: str = None, + **kwargs) -> 'DetailedResponse': """ Add a custom word. @@ -750,7 +765,9 @@ def add_word(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', '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 = {'translation': translation, 'part_of_speech': part_of_speech} @@ -760,12 +777,13 @@ def add_word(self, request = self.prepare_request(method='PUT', url=url, headers=headers, - data=data, - accept_json=False) + data=data) + response = self.send(request) return response - def get_word(self, customization_id, word, **kwargs): + def get_word(self, customization_id: str, word: str, + **kwargs) -> 'DetailedResponse': """ Get a custom word. @@ -794,19 +812,20 @@ def get_word(self, customization_id, word, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'get_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_word(self, customization_id, word, **kwargs): + def delete_word(self, customization_id: str, word: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom word. @@ -834,15 +853,17 @@ def delete_word(self, customization_id, word, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'delete_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -850,7 +871,8 @@ def delete_word(self, customization_id, word, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -877,8 +899,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - '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 = {'customer_id': customer_id} @@ -887,8 +910,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -956,6 +979,7 @@ class Voice(Enum): """ The voice to use for synthesis. """ + AR_AR_OMARVOICE = 'ar-AR_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' @@ -982,8 +1006,13 @@ class Voice(Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' + NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' + ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' + ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class GetPronunciationEnums(object): @@ -1066,7 +1095,7 @@ class Pronunciation(): pronunciation also reflects that custom voice. """ - def __init__(self, pronunciation): + def __init__(self, pronunciation: str) -> None: """ Initialize a Pronunciation object. @@ -1077,7 +1106,7 @@ def __init__(self, pronunciation): self.pronunciation = pronunciation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} valid_keys = ['pronunciation'] @@ -1094,24 +1123,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pronunciation 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, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict - def __str__(self): + 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 Pronunciation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pronunciation') -> 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): + def __ne__(self, other: 'Pronunciation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1127,7 +1165,8 @@ class SupportedFeatures(): cannot be transformed. """ - def __init__(self, custom_pronunciation, voice_transformation): + def __init__(self, custom_pronunciation: bool, + voice_transformation: bool) -> None: """ Initialize a SupportedFeatures object. @@ -1141,7 +1180,7 @@ def __init__(self, custom_pronunciation, voice_transformation): self.voice_transformation = voice_transformation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} valid_keys = ['custom_pronunciation', 'voice_transformation'] @@ -1164,7 +1203,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SupportedFeatures 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, 'custom_pronunciation' @@ -1175,17 +1219,21 @@ def _to_dict(self): _dict['voice_transformation'] = self.voice_transformation return _dict - def __str__(self): + 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 SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SupportedFeatures') -> 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): + def __ne__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1206,7 +1254,7 @@ class Translation(): entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, translation, *, part_of_speech=None): + def __init__(self, translation: str, *, part_of_speech: str = None) -> None: """ Initialize a Translation object. @@ -1227,7 +1275,7 @@ def __init__(self, translation, *, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} valid_keys = ['translation', 'part_of_speech'] @@ -1246,7 +1294,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Translation 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, 'translation') and self.translation is not None: @@ -1255,17 +1308,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 Translation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Translation') -> 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): + def __ne__(self, other: 'Translation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1318,15 +1375,15 @@ class Voice(): """ def __init__(self, - url, - gender, - name, - language, - description, - customizable, - supported_features, + url: str, + gender: str, + name: str, + language: str, + description: str, + customizable: bool, + supported_features: 'SupportedFeatures', *, - customization=None): + customization: 'VoiceModel' = None) -> None: """ Initialize a Voice object. @@ -1357,7 +1414,7 @@ def __init__(self, self.customization = customization @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} valid_keys = [ @@ -1411,7 +1468,12 @@ def _from_dict(cls, _dict): _dict.get('customization')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Voice 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, 'url') and self.url is not None: @@ -1434,17 +1496,21 @@ def _to_dict(self): _dict['customization'] = self.customization._to_dict() return _dict - def __str__(self): + 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 Voice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Voice') -> 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): + def __ne__(self, other: 'Voice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1470,7 +1536,7 @@ class VoiceModel(): 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 voice model. - :attr list[Word] words: (optional) An array of `Word` objects that lists the + :attr List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. This field is returned @@ -1479,15 +1545,15 @@ class VoiceModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - name=None, - language=None, - owner=None, - created=None, - last_modified=None, - description=None, - words=None): + name: str = None, + language: str = None, + owner: str = None, + created: str = None, + last_modified: str = None, + description: str = None, + words: List['Word'] = None) -> None: """ Initialize a VoiceModel object. @@ -1509,7 +1575,7 @@ def __init__(self, (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str description: (optional) The description of the custom voice model. - :param list[Word] words: (optional) An array of `Word` objects that lists + :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no @@ -1526,7 +1592,7 @@ def __init__(self, self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'VoiceModel': """Initialize a VoiceModel object from a json dictionary.""" args = {} valid_keys = [ @@ -1560,7 +1626,12 @@ def _from_dict(cls, _dict): args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a VoiceModel 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, @@ -1582,17 +1653,21 @@ def _to_dict(self): _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 VoiceModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'VoiceModel') -> 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): + def __ne__(self, other: 'VoiceModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1601,17 +1676,17 @@ class VoiceModels(): """ Information about existing custom voice models. - :attr list[VoiceModel] customizations: An array of `VoiceModel` objects that + :attr List[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified language. """ - def __init__(self, customizations): + def __init__(self, customizations: List['VoiceModel']) -> None: """ Initialize a VoiceModels object. - :param list[VoiceModel] customizations: An array of `VoiceModel` objects + :param List[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified @@ -1620,7 +1695,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'VoiceModels': """Initialize a VoiceModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -1639,7 +1714,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a VoiceModels 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, 'customizations') and self.customizations is not None: @@ -1648,17 +1728,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 VoiceModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'VoiceModels') -> 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): + def __ne__(self, other: 'VoiceModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1667,19 +1751,19 @@ class Voices(): """ Information about all available voice models. - :attr list[Voice] voices: A list of available voices. + :attr List[Voice] voices: A list of available voices. """ - def __init__(self, voices): + def __init__(self, voices: List['Voice']) -> None: """ Initialize a Voices object. - :param list[Voice] voices: A list of available voices. + :param List[Voice] voices: A list of available voices. """ self.voices = voices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} valid_keys = ['voices'] @@ -1697,24 +1781,33 @@ def _from_dict(cls, _dict): 'Required property \'voices\' not present in Voices JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Voices 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, 'voices') and self.voices is not None: _dict['voices'] = [x._to_dict() for x in self.voices] return _dict - def __str__(self): + 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 Voices object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Voices') -> 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): + def __ne__(self, other: 'Voices') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1737,7 +1830,11 @@ class Word(): entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, word, translation, *, part_of_speech=None): + def __init__(self, + word: str, + translation: str, + *, + part_of_speech: str = None) -> None: """ Initialize a Word object. @@ -1760,7 +1857,7 @@ def __init__(self, word, translation, *, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} valid_keys = ['word', 'translation', 'part_of_speech'] @@ -1783,7 +1880,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Word 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, 'word') and self.word is not None: @@ -1794,17 +1896,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 Word object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Word') -> 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): + def __ne__(self, other: 'Word') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1843,7 +1949,7 @@ class Words(): For the **List custom words** method, the words and their translations from the custom voice model. - :attr list[Word] words: The **Add custom words** method accepts an array of + :attr List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object @@ -1852,11 +1958,11 @@ class Words(): letters. The array is empty if the custom model contains no words. """ - def __init__(self, words): + def __init__(self, words: List['Word']) -> None: """ Initialize a Words object. - :param list[Word] words: The **Add custom words** method accepts an array + :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each @@ -1868,7 +1974,7 @@ def __init__(self, words): self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} valid_keys = ['words'] @@ -1884,23 +1990,32 @@ def _from_dict(cls, _dict): 'Required property \'words\' not present in Words JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Words 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, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 Words object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Words') -> 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): + def __ne__(self, other: 'Words') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 454ce955c..2d8efd6f1 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,248 +1,1224 @@ -# coding=utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -@responses.activate -def test_success(): - voices_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices' - voices_response = { - "voices": [{ - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsLisa", - "gender": - "female", - "name": - "VoiceEnUsLisa", - "language": - "en-US" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEsEsEnrique", - "gender": - "male", - "name": - "VoiceEsEsEnrique", - "language": - "es-ES" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsMichael", - "gender": - "male", - "name": - "VoiceEnUsMichael", - "language": - "en-US" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsAllison", - "gender": - "female", - "name": - "VoiceEnUsAllison", - "language": - "en-US" - }] - } - voice_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-us_AllisonVoice' - voice_response = { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-US_AllisonVoice", - "name": - "en-US_AllisonVoice", - "language": - "en-US", - "customizable": - True, - "gender": - "female", - "description": - "Allison: American English female voice.", - "supported_features": { - "custom_pronunciation": True, - "voice_transformation": True - } - } - synthesize_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize' - synthesize_response_body = '' - - responses.add( - responses.GET, - voices_url, - body=json.dumps(voices_response), - status=200, - content_type='application/json') - responses.add( - responses.GET, - voice_url, - body=json.dumps(voice_response), - status=200, - content_type='application/json') - responses.add( - responses.POST, - synthesize_url, - body=synthesize_response_body, - status=200, - content_type='application/json', - match_querystring=True) - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_voices() - assert responses.calls[0].request.url == voices_url - assert responses.calls[0].response.text == json.dumps(voices_response) - - text_to_speech.get_voice('en-us_AllisonVoice') - assert responses.calls[1].request.url == voice_url - assert responses.calls[1].response.text == json.dumps(voice_response) - - text_to_speech.synthesize('hello') - assert responses.calls[2].request.url == synthesize_url - assert responses.calls[2].response.text == synthesize_response_body - - assert len(responses.calls) == 3 - - -@responses.activate -def test_get_pronunciation(): - - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/pronunciation', - body='{"pronunciation": "pronunciation info" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.get_pronunciation(text="this is some text") - text_to_speech.get_pronunciation(text="yo", voice="VoiceEnUsLisa") - text_to_speech.get_pronunciation( - text="yo", voice="VoiceEnUsLisa", format='ipa') - - assert len(responses.calls) == 3 - - -@responses.activate -def test_custom_voice_models(): - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customization": "yep, just one" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_voice_models() - text_to_speech.list_voice_models(language="en-US") - assert len(responses.calls) == 2 - - text_to_speech.create_voice_model(name="name", description="description") - text_to_speech.get_voice_model(customization_id='custid') - text_to_speech.update_voice_model( - customization_id="custid", name="name", description="description") - text_to_speech.delete_voice_model(customization_id="custid") - - assert len(responses.calls) == 6 - - -@responses.activate -def test_custom_words(): - base_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations' - responses.add( - responses.GET, - "{0}/{1}/words".format(base_url, "custid"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - "{0}/{1}/words".format(base_url, "custid"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.GET, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customization": "yep, just one" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.PUT, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_words(customization_id="custid") - text_to_speech.add_words( - customization_id="custid", words=[{"word": "one", "translation": "one"}, {"word": "two", "translation": "two"}]) - text_to_speech.get_word(customization_id="custid", word="word") - text_to_speech.add_word( - customization_id='custid', word="word", translation="I'm translated") - text_to_speech.delete_word(customization_id="custid", word="word") - - assert len(responses.calls) == 5 - -@responses.activate - -def test_delete_user_data(): - url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - response = text_to_speech.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 +import pytest +import responses +import tempfile +import ibm_watson.text_to_speech_v1 +from ibm_watson.text_to_speech_v1 import * + +base_url = 'https://stream.watsonplatform.net/text-to-speech/api' + +############################################################################## +# Start of Service: Voices +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_voices +#----------------------------------------------------------------------------- +class TestListVoices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voices_response(self): + body = self.construct_full_body() + response = fake_response_Voices_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Voices_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voices_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/voices' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_voices(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_voice +#----------------------------------------------------------------------------- +class TestGetVoice(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_response(self): + body = self.construct_full_body() + response = fake_response_Voice_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Voice_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_empty(self): + check_empty_required_params(self, fake_response_Voice_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/voices/{0}'.format(body['voice']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_voice(**body) + return output + + def construct_full_body(self): + body = dict() + body['voice'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['voice'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Voices +############################################################################## + +############################################################################## +# Start of Service: Synthesis +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for synthesize +#----------------------------------------------------------------------------- +class TestSynthesize(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_synthesize_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_synthesize_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_synthesize_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/synthesize' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.synthesize(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "text": "string1", + }) + body['accept'] = "string1" + body['voice'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({ + "text": "string1", + }) + return body + + +# endregion +############################################################################## +# End of Service: Synthesis +############################################################################## + +############################################################################## +# Start of Service: Pronunciation +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for get_pronunciation +#----------------------------------------------------------------------------- +class TestGetPronunciation(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_pronunciation_response(self): + body = self.construct_full_body() + response = fake_response_Pronunciation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_pronunciation_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Pronunciation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_pronunciation_empty(self): + check_empty_required_params(self, fake_response_Pronunciation_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/pronunciation' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_pronunciation(**body) + return output + + def construct_full_body(self): + body = dict() + body['text'] = "string1" + body['voice'] = "string1" + body['format'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Pronunciation +############################################################################## + +############################################################################## +# Start of Service: CustomModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_voice_model +#----------------------------------------------------------------------------- +class TestCreateVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_voice_model_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_voice_model_empty(self): + check_empty_required_params(self, fake_response_VoiceModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "language": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "language": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_voice_models +#----------------------------------------------------------------------------- +class TestListVoiceModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voice_models_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voice_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voice_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_voice_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_voice_model +#----------------------------------------------------------------------------- +class TestUpdateVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_voice_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_voice_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.update_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "name": "string1", + "description": "string1", + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "name": "string1", + "description": "string1", + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_voice_model +#----------------------------------------------------------------------------- +class TestGetVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_model_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_model_empty(self): + check_empty_required_params(self, fake_response_VoiceModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_voice_model +#----------------------------------------------------------------------------- +class TestDeleteVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_voice_model_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_voice_model_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomModels +############################################################################## + +############################################################################## +# Start of Service: CustomWords +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for add_words +#----------------------------------------------------------------------------- +class TestAddWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_words +#----------------------------------------------------------------------------- +class TestListWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_response(self): + body = self.construct_full_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_empty(self): + check_empty_required_params(self, fake_response_Words_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_word +#----------------------------------------------------------------------------- +class TestAddWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + body.update({ + "translation": "string1", + "part_of_speech": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + body.update({ + "translation": "string1", + "part_of_speech": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_word +#----------------------------------------------------------------------------- +class TestGetWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_response(self): + body = self.construct_full_body() + response = fake_response_Translation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Translation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_empty(self): + check_empty_required_params(self, fake_response_Translation_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_word +#----------------------------------------------------------------------------- +class TestDeleteWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomWords +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Voices_json = """{"voices": []}""" +fake_response_Voice_json = """{"url": "fake_url", "gender": "fake_gender", "name": "fake_name", "language": "fake_language", "description": "fake_description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" +fake_response_Pronunciation_json = """{"pronunciation": "fake_pronunciation"}""" +fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_VoiceModels_json = """{"customizations": []}""" +fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_Words_json = """{"words": []}""" +fake_response_Translation_json = """{"translation": "fake_translation", "part_of_speech": "fake_part_of_speech"}""" From 88106fb9c9460e60363a814565b51a512805f8b9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:19:39 -0500 Subject: [PATCH 21/28] feat(core): Update core version --- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 282f872f9..4c72280d9 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0 +ibm_cloud_sdk_core==1.5.1 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index d5fca9ef9..fea3e1c8c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0 +ibm_cloud_sdk_core==1.5.1 diff --git a/setup.py b/setup.py index fb53120b9..8e949081a 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.5.1'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 6efe91ddb8608db85d3c855a821bd3edc0e262a2 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:26:23 -0500 Subject: [PATCH 22/28] chore(style): run yapf on tests --- test/unit/test_assistant_v1.py | 1080 +++++++++----- test/unit/test_assistant_v2.py | 61 +- test/unit/test_common.py | 7 +- test/unit/test_compare_comply_v1.py | 178 ++- test/unit/test_discovery_v1.py | 1261 +++++++++++------ test/unit/test_discovery_v2.py | 274 ++-- test/unit/test_language_translator_v3.py | 172 ++- .../test_natural_language_understanding.py | 146 -- 8 files changed, 1958 insertions(+), 1221 deletions(-) delete mode 100644 test/unit/test_natural_language_understanding.py diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 458f26b46..59237d056 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -29,6 +29,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -74,16 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -91,7 +92,25 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) + body.update({ + "input": + MessageInput._from_dict(json.loads("""{"text": "fake_text"}""") + ), + "intents": [], + "entities": [], + "alternate_intents": + True, + "context": + Context._from_dict( + json.loads( + """{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""" + )), + "output": + OutputData._from_dict( + json.loads( + """{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""" + )), + }) body['nodes_visited_details'] = True return body @@ -111,6 +130,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_workspaces #----------------------------------------------------------------------------- @@ -155,16 +175,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_workspaces(**body) return output @@ -226,23 +246,45 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_workspace(**body) return output def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "system_settings": WorkspaceSystemSettings._from_dict(json.loads("""{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({ + "name": + "string1", + "description": + "string1", + "language": + "string1", + "metadata": { + "mock": "data" + }, + "learning_opt_out": + True, + "system_settings": + WorkspaceSystemSettings._from_dict( + json.loads( + """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""" + )), + "intents": [], + "entities": [], + "dialog_nodes": [], + "counterexamples": [], + "webhooks": [], + }) return body def construct_required_body(self): @@ -295,16 +337,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_workspace(**body) return output @@ -368,16 +410,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_workspace(**body) return output @@ -385,7 +427,29 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "system_settings": WorkspaceSystemSettings._from_dict(json.loads("""{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({ + "name": + "string1", + "description": + "string1", + "language": + "string1", + "metadata": { + "mock": "data" + }, + "learning_opt_out": + True, + "system_settings": + WorkspaceSystemSettings._from_dict( + json.loads( + """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""" + )), + "intents": [], + "entities": [], + "dialog_nodes": [], + "counterexamples": [], + "webhooks": [], + }) body['append'] = True return body @@ -440,16 +504,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_workspace(**body) return output @@ -475,6 +539,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_intents #----------------------------------------------------------------------------- @@ -520,16 +585,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_intents(**body) return output @@ -595,16 +660,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_intent(**body) return output @@ -612,13 +677,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) + body.update({ + "intent": "string1", + "description": "string1", + "examples": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) + body.update({ + "intent": "string1", + "description": "string1", + "examples": [], + }) return body @@ -661,22 +734,23 @@ def test_get_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_intent(**body) return output @@ -735,22 +809,23 @@ def test_update_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_intent(**body) return output @@ -759,14 +834,22 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + body.update({ + "new_intent": "string1", + "new_description": "string1", + "new_examples": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + body.update({ + "new_intent": "string1", + "new_description": "string1", + "new_examples": [], + }) return body @@ -809,22 +892,23 @@ def test_delete_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_intent(**body) return output @@ -852,6 +936,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_examples #----------------------------------------------------------------------------- @@ -891,22 +976,23 @@ def test_list_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( + body['workspace_id'], body['intent']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_examples(**body) return output @@ -967,22 +1053,23 @@ def test_create_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( + body['workspace_id'], body['intent']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_example(**body) return output @@ -991,14 +1078,20 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) + body.update({ + "text": "string1", + "mentions": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) + body.update({ + "text": "string1", + "mentions": [], + }) return body @@ -1041,22 +1134,23 @@ def test_get_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_example(**body) return output @@ -1116,22 +1210,23 @@ def test_update_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_example(**body) return output @@ -1141,7 +1236,10 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) + body.update({ + "new_text": "string1", + "new_mentions": [], + }) return body def construct_required_body(self): @@ -1149,7 +1247,10 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) + body.update({ + "new_text": "string1", + "new_mentions": [], + }) return body @@ -1192,22 +1293,23 @@ def test_delete_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_example(**body) return output @@ -1237,6 +1339,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_counterexamples #----------------------------------------------------------------------------- @@ -1268,7 +1371,8 @@ def test_list_counterexamples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_counterexamples_empty(self): - check_empty_required_params(self, fake_response_CounterexampleCollection_json) + check_empty_required_params( + self, fake_response_CounterexampleCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1276,22 +1380,23 @@ def test_list_counterexamples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format( + body['workspace_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_counterexamples(**body) return output @@ -1350,22 +1455,23 @@ def test_create_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format( + body['workspace_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_counterexample(**body) return output @@ -1373,13 +1479,17 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"text": "string1", }) + body.update({ + "text": "string1", + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"text": "string1", }) + body.update({ + "text": "string1", + }) return body @@ -1422,22 +1532,23 @@ def test_get_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_counterexample(**body) return output @@ -1495,22 +1606,23 @@ def test_update_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_counterexample(**body) return output @@ -1519,14 +1631,18 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", }) + body.update({ + "new_text": "string1", + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", }) + body.update({ + "new_text": "string1", + }) return body @@ -1569,22 +1685,23 @@ def test_delete_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_counterexample(**body) return output @@ -1612,6 +1729,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_entities #----------------------------------------------------------------------------- @@ -1657,16 +1775,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_entities(**body) return output @@ -1732,16 +1850,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_entity(**body) return output @@ -1749,13 +1867,29 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + body.update({ + "entity": "string1", + "description": "string1", + "metadata": { + "mock": "data" + }, + "fuzzy_match": True, + "values": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + body.update({ + "entity": "string1", + "description": "string1", + "metadata": { + "mock": "data" + }, + "fuzzy_match": True, + "values": [], + }) return body @@ -1798,22 +1932,23 @@ def test_get_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_entity(**body) return output @@ -1872,22 +2007,23 @@ def test_update_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_entity(**body) return output @@ -1896,14 +2032,30 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + body.update({ + "new_entity": "string1", + "new_description": "string1", + "new_metadata": { + "mock": "data" + }, + "new_fuzzy_match": True, + "new_values": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + body.update({ + "new_entity": "string1", + "new_description": "string1", + "new_metadata": { + "mock": "data" + }, + "new_fuzzy_match": True, + "new_values": [], + }) return body @@ -1946,22 +2098,23 @@ def test_delete_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_entity(**body) return output @@ -1989,6 +2142,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_mentions #----------------------------------------------------------------------------- @@ -2020,7 +2174,8 @@ def test_list_mentions_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_mentions_empty(self): - check_empty_required_params(self, fake_response_EntityMentionCollection_json) + check_empty_required_params(self, + fake_response_EntityMentionCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2028,22 +2183,23 @@ def test_list_mentions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_mentions(**body) return output @@ -2073,6 +2229,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_values #----------------------------------------------------------------------------- @@ -2112,22 +2269,23 @@ def test_list_values_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_values(**body) return output @@ -2189,22 +2347,23 @@ def test_create_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( + body['workspace_id'], body['entity']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_value(**body) return output @@ -2213,14 +2372,30 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + body.update({ + "value": "string1", + "metadata": { + "mock": "data" + }, + "type": "string1", + "synonyms": [], + "patterns": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + body.update({ + "value": "string1", + "metadata": { + "mock": "data" + }, + "type": "string1", + "synonyms": [], + "patterns": [], + }) return body @@ -2263,22 +2438,23 @@ def test_get_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_value(**body) return output @@ -2339,22 +2515,23 @@ def test_update_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_value(**body) return output @@ -2364,7 +2541,15 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + body.update({ + "new_value": "string1", + "new_metadata": { + "mock": "data" + }, + "new_type": "string1", + "new_synonyms": [], + "new_patterns": [], + }) return body def construct_required_body(self): @@ -2372,7 +2557,15 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + body.update({ + "new_value": "string1", + "new_metadata": { + "mock": "data" + }, + "new_type": "string1", + "new_synonyms": [], + "new_patterns": [], + }) return body @@ -2415,22 +2608,23 @@ def test_delete_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_value(**body) return output @@ -2460,6 +2654,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_synonyms #----------------------------------------------------------------------------- @@ -2499,22 +2694,23 @@ def test_list_synonyms_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( + body['workspace_id'], body['entity'], body['value']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_synonyms(**body) return output @@ -2577,22 +2773,23 @@ def test_create_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( + body['workspace_id'], body['entity'], body['value']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_synonym(**body) return output @@ -2602,7 +2799,9 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"synonym": "string1", }) + body.update({ + "synonym": "string1", + }) return body def construct_required_body(self): @@ -2610,7 +2809,9 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"synonym": "string1", }) + body.update({ + "synonym": "string1", + }) return body @@ -2653,22 +2854,24 @@ def test_get_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_synonym(**body) return output @@ -2730,22 +2933,24 @@ def test_update_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_synonym(**body) return output @@ -2756,7 +2961,9 @@ def construct_full_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) + body.update({ + "new_synonym": "string1", + }) return body def construct_required_body(self): @@ -2765,7 +2972,9 @@ def construct_required_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) + body.update({ + "new_synonym": "string1", + }) return body @@ -2808,22 +3017,24 @@ def test_delete_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_synonym(**body) return output @@ -2855,6 +3066,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_dialog_nodes #----------------------------------------------------------------------------- @@ -2886,7 +3098,8 @@ def test_list_dialog_nodes_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_dialog_nodes_empty(self): - check_empty_required_params(self, fake_response_DialogNodeCollection_json) + check_empty_required_params(self, + fake_response_DialogNodeCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2894,22 +3107,23 @@ def test_list_dialog_nodes_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( + body['workspace_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_dialog_nodes(**body) return output @@ -2968,22 +3182,23 @@ def test_create_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( + body['workspace_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_dialog_node(**body) return output @@ -2991,13 +3206,105 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({ + "dialog_node": + "string1", + "description": + "string1", + "conditions": + "string1", + "parent": + "string1", + "previous_sibling": + "string1", + "output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "context": { + "mock": "data" + }, + "metadata": { + "mock": "data" + }, + "next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "title": + "string1", + "type": + "string1", + "event_name": + "string1", + "variable": + "string1", + "actions": [], + "digress_in": + "string1", + "digress_out": + "string1", + "digress_out_slots": + "string1", + "user_label": + "string1", + "disambiguation_opt_out": + True, + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({ + "dialog_node": + "string1", + "description": + "string1", + "conditions": + "string1", + "parent": + "string1", + "previous_sibling": + "string1", + "output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "context": { + "mock": "data" + }, + "metadata": { + "mock": "data" + }, + "next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "title": + "string1", + "type": + "string1", + "event_name": + "string1", + "variable": + "string1", + "actions": [], + "digress_in": + "string1", + "digress_out": + "string1", + "digress_out_slots": + "string1", + "user_label": + "string1", + "disambiguation_opt_out": + True, + }) return body @@ -3040,22 +3347,23 @@ def test_get_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_dialog_node(**body) return output @@ -3113,22 +3421,23 @@ def test_update_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_dialog_node(**body) return output @@ -3137,14 +3446,106 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({ + "new_dialog_node": + "string1", + "new_description": + "string1", + "new_conditions": + "string1", + "new_parent": + "string1", + "new_previous_sibling": + "string1", + "new_output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "new_context": { + "mock": "data" + }, + "new_metadata": { + "mock": "data" + }, + "new_next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "new_title": + "string1", + "new_type": + "string1", + "new_event_name": + "string1", + "new_variable": + "string1", + "new_actions": [], + "new_digress_in": + "string1", + "new_digress_out": + "string1", + "new_digress_out_slots": + "string1", + "new_user_label": + "string1", + "new_disambiguation_opt_out": + True, + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({ + "new_dialog_node": + "string1", + "new_description": + "string1", + "new_conditions": + "string1", + "new_parent": + "string1", + "new_previous_sibling": + "string1", + "new_output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "new_context": { + "mock": "data" + }, + "new_metadata": { + "mock": "data" + }, + "new_next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "new_title": + "string1", + "new_type": + "string1", + "new_event_name": + "string1", + "new_variable": + "string1", + "new_actions": [], + "new_digress_in": + "string1", + "new_digress_out": + "string1", + "new_digress_out_slots": + "string1", + "new_user_label": + "string1", + "new_disambiguation_opt_out": + True, + }) return body @@ -3187,22 +3588,23 @@ def test_delete_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_dialog_node(**body) return output @@ -3230,6 +3632,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_logs #----------------------------------------------------------------------------- @@ -3275,16 +3678,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_logs(**body) return output @@ -3349,16 +3752,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_all_logs(**body) return output @@ -3387,6 +3790,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3432,16 +3836,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - + url, + body=json.dumps(response), + status=202, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3479,6 +3883,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -3495,6 +3900,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -3506,6 +3912,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -3522,6 +3929,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a43dd8c1b..0c2cb1abd 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -28,6 +28,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_session #----------------------------------------------------------------------------- @@ -73,16 +74,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_session(**body) return output @@ -137,22 +138,23 @@ def test_delete_session_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}'.format( + body['assistant_id'], body['session_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_session(**body) return output @@ -180,6 +182,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -219,22 +222,23 @@ def test_message_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format( + body['assistant_id'], body['session_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -243,7 +247,18 @@ def construct_full_body(self): body = dict() body['assistant_id'] = "string1" body['session_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""")), }) + body.update({ + "input": + MessageInput._from_dict( + json.loads( + """{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""" + )), + "context": + MessageContext._from_dict( + json.loads( + """{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""" + )), + }) return body def construct_required_body(self): @@ -275,6 +290,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -291,6 +307,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -302,6 +319,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -318,6 +336,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_common.py b/test/unit/test_common.py index a2553e86f..110f26259 100644 --- a/test/unit/test_common.py +++ b/test/unit/test_common.py @@ -17,11 +17,16 @@ from ibm_watson import get_sdk_headers import unittest + class TestCommon(unittest.TestCase): + def test_get_sdk_headers(self): headers = get_sdk_headers('my_service', 'v1', 'my_operation') self.assertIsNotNone(headers) self.assertIsNotNone(headers.get('X-IBMCloud-SDK-Analytics')) self.assertIsNotNone(headers.get('User-Agent')) self.assertIn('watson-apis-python-sdk', headers.get('User-Agent')) - self.assertEqual(headers.get('X-IBMCloud-SDK-Analytics'), 'service_name=my_service;service_version=v1;operation_id=my_operation') + self.assertEqual( + headers.get('X-IBMCloud-SDK-Analytics'), + 'service_name=my_service;service_version=v1;operation_id=my_operation' + ) diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 0100cabe8..171458bd1 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for convert_to_html #----------------------------------------------------------------------------- @@ -75,16 +76,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.convert_to_html(**body) return output @@ -112,6 +113,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for classify_elements #----------------------------------------------------------------------------- @@ -157,16 +159,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.classify_elements(**body) return output @@ -194,6 +196,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for extract_tables #----------------------------------------------------------------------------- @@ -239,16 +242,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.extract_tables(**body) return output @@ -276,6 +279,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for compare_documents #----------------------------------------------------------------------------- @@ -321,16 +325,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.compare_documents(**body) return output @@ -363,6 +367,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_feedback #----------------------------------------------------------------------------- @@ -408,28 +413,48 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.add_feedback(**body) return output def construct_full_body(self): body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + body.update({ + "feedback_data": + FeedbackDataInput._from_dict( + json.loads( + """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" + )), + "user_id": + "string1", + "comment": + "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + body.update({ + "feedback_data": + FeedbackDataInput._from_dict( + json.loads( + """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" + )), + "user_id": + "string1", + "comment": + "string1", + }) return body @@ -477,16 +502,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_feedback(**body) return output @@ -561,16 +586,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_feedback(**body) return output @@ -632,16 +657,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.delete_feedback(**body) return output @@ -668,6 +693,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_batch #----------------------------------------------------------------------------- @@ -713,16 +739,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.create_batch(**body) return output @@ -795,16 +821,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_batches(**body) return output @@ -863,16 +889,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_batch(**body) return output @@ -933,16 +959,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.update_batch(**body) return output @@ -983,6 +1009,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -999,6 +1026,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1010,6 +1038,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1026,6 +1055,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index e1ed74b89..363c5d6e9 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_environment #----------------------------------------------------------------------------- @@ -75,28 +76,36 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_environment(**body) return output def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body @@ -144,16 +153,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_environments(**body) return output @@ -213,16 +222,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_environment(**body) return output @@ -283,16 +292,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_environment(**body) return output @@ -300,13 +309,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body @@ -341,7 +358,8 @@ def test_delete_environment_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_environment_empty(self): - check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) + check_empty_required_params( + self, fake_response_DeleteEnvironmentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -355,16 +373,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_environment(**body) return output @@ -411,7 +429,8 @@ def test_list_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params( + self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -425,16 +444,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -462,6 +481,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_configuration #----------------------------------------------------------------------------- @@ -501,22 +521,23 @@ def test_create_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_configuration(**body) return output @@ -524,13 +545,47 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body @@ -565,7 +620,8 @@ def test_list_configurations_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_configurations_empty(self): - check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) + check_empty_required_params( + self, fake_response_ListConfigurationsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -573,22 +629,23 @@ def test_list_configurations_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_configurations(**body) return output @@ -644,22 +701,23 @@ def test_get_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_configuration(**body) return output @@ -716,22 +774,23 @@ def test_update_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_configuration(**body) return output @@ -740,14 +799,48 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body @@ -782,7 +875,8 @@ def test_delete_configuration_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_configuration_empty(self): - check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) + check_empty_required_params( + self, fake_response_DeleteConfigurationResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -790,22 +884,23 @@ def test_delete_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_configuration(**body) return output @@ -833,6 +928,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_collection #----------------------------------------------------------------------------- @@ -872,22 +968,23 @@ def test_create_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_collection(**body) return output @@ -895,13 +992,23 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + "language": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + "language": "string1", + }) return body @@ -936,7 +1043,8 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, + fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -944,22 +1052,23 @@ def test_list_collections_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -1015,22 +1124,23 @@ def test_get_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_collection(**body) return output @@ -1087,22 +1197,23 @@ def test_update_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_collection(**body) return output @@ -1111,14 +1222,22 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + }) return body @@ -1153,7 +1272,8 @@ def test_delete_collection_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_collection_empty(self): - check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) + check_empty_required_params( + self, fake_response_DeleteCollectionResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1161,22 +1281,23 @@ def test_delete_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_collection(**body) return output @@ -1225,7 +1346,8 @@ def test_list_collection_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collection_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params( + self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1233,22 +1355,23 @@ def test_list_collection_fields_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/fields'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collection_fields(**body) return output @@ -1276,6 +1399,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_expansions #----------------------------------------------------------------------------- @@ -1315,22 +1439,23 @@ def test_list_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_expansions(**body) return output @@ -1387,22 +1512,23 @@ def test_create_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_expansions(**body) return output @@ -1411,14 +1537,18 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"expansions": [], }) + body.update({ + "expansions": [], + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"expansions": [], }) + body.update({ + "expansions": [], + }) return body @@ -1461,22 +1591,23 @@ def test_delete_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_expansions(**body) return output @@ -1525,7 +1656,8 @@ def test_get_tokenization_dictionary_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_tokenization_dictionary_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1533,22 +1665,23 @@ def test_get_tokenization_dictionary_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_tokenization_dictionary_status(**body) return output @@ -1597,7 +1730,8 @@ def test_create_tokenization_dictionary_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_tokenization_dictionary_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1605,22 +1739,23 @@ def test_create_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_tokenization_dictionary(**body) return output @@ -1629,7 +1764,9 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"tokenization_rules": [], }) + body.update({ + "tokenization_rules": [], + }) return body def construct_required_body(self): @@ -1678,22 +1815,23 @@ def test_delete_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_tokenization_dictionary(**body) return output @@ -1742,7 +1880,8 @@ def test_get_stopword_list_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_stopword_list_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1750,22 +1889,23 @@ def test_get_stopword_list_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_stopword_list_status(**body) return output @@ -1814,7 +1954,8 @@ def test_create_stopword_list_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_stopword_list_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1822,22 +1963,23 @@ def test_create_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_stopword_list(**body) return output @@ -1897,22 +2039,23 @@ def test_delete_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_stopword_list(**body) return output @@ -1940,6 +2083,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -1979,22 +2123,23 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -2055,22 +2200,23 @@ def test_get_document_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -2129,22 +2275,23 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -2199,7 +2346,8 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, + fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2207,22 +2355,23 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -2252,6 +2401,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -2291,22 +2441,23 @@ def test_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/query'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -2315,7 +2466,28 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) + body.update({ + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + "spelling_suggestions": True, + }) body['x_watson_logging_opt_out'] = True return body @@ -2357,7 +2529,8 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2365,22 +2538,23 @@ def test_query_notices_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/notices'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -2460,16 +2634,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query(**body) return output @@ -2477,14 +2651,56 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body.update({ + "collection_ids": "string1", + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + }) body['x_watson_logging_opt_out'] = True return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body.update({ + "collection_ids": "string1", + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + }) return body @@ -2519,7 +2735,8 @@ def test_federated_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_federated_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2533,16 +2750,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query_notices(**body) return output @@ -2612,22 +2829,23 @@ def test_get_autocompletion_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -2659,6 +2877,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_training_data #----------------------------------------------------------------------------- @@ -2698,22 +2917,23 @@ def test_list_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_data(**body) return output @@ -2770,22 +2990,23 @@ def test_add_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_training_data(**body) return output @@ -2794,14 +3015,22 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [], + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [], + }) return body @@ -2844,22 +3073,23 @@ def test_delete_all_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_all_training_data(**body) return output @@ -2916,22 +3146,23 @@ def test_get_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( + body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_data(**body) return output @@ -2990,22 +3221,23 @@ def test_delete_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( + body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_data(**body) return output @@ -3056,7 +3288,8 @@ def test_list_training_examples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_training_examples_empty(self): - check_empty_required_params(self, fake_response_TrainingExampleList_json) + check_empty_required_params(self, + fake_response_TrainingExampleList_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3064,22 +3297,23 @@ def test_list_training_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( + body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_examples(**body) return output @@ -3138,22 +3372,23 @@ def test_create_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( + body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_training_example(**body) return output @@ -3163,7 +3398,11 @@ def construct_full_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + body.update({ + "document_id": "string1", + "cross_reference": "string1", + "relevance": 12345, + }) return body def construct_required_body(self): @@ -3171,7 +3410,11 @@ def construct_required_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + body.update({ + "document_id": "string1", + "cross_reference": "string1", + "relevance": 12345, + }) return body @@ -3214,22 +3457,24 @@ def test_delete_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_example(**body) return output @@ -3290,22 +3535,24 @@ def test_update_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_training_example(**body) return output @@ -3316,7 +3563,10 @@ def construct_full_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) + body.update({ + "cross_reference": "string1", + "relevance": 12345, + }) return body def construct_required_body(self): @@ -3325,7 +3575,10 @@ def construct_required_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) + body.update({ + "cross_reference": "string1", + "relevance": 12345, + }) return body @@ -3368,22 +3621,24 @@ def test_get_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_example(**body) return output @@ -3415,6 +3670,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3460,16 +3716,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3495,6 +3751,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_event #----------------------------------------------------------------------------- @@ -3526,7 +3783,8 @@ def test_create_event_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_event_empty(self): - check_empty_required_params(self, fake_response_CreateEventResponse_json) + check_empty_required_params(self, + fake_response_CreateEventResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3540,28 +3798,44 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_event(**body) return output def construct_full_body(self): body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + body.update({ + "type": + "string1", + "data": + EventData._from_dict( + json.loads( + """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" + )), + }) return body def construct_required_body(self): body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + body.update({ + "type": + "string1", + "data": + EventData._from_dict( + json.loads( + """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" + )), + }) return body @@ -3609,16 +3883,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_log(**body) return output @@ -3681,16 +3955,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query(**body) return output @@ -3751,16 +4025,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_event(**body) return output @@ -3821,16 +4095,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_no_results(**body) return output @@ -3891,16 +4165,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_event_rate(**body) return output @@ -3961,16 +4235,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_token_event(**body) return output @@ -3995,6 +4269,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_credentials #----------------------------------------------------------------------------- @@ -4034,22 +4309,23 @@ def test_list_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_credentials(**body) return output @@ -4104,22 +4380,23 @@ def test_create_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_credentials(**body) return output @@ -4127,13 +4404,33 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body @@ -4176,22 +4473,23 @@ def test_get_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_credentials(**body) return output @@ -4248,22 +4546,23 @@ def test_update_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_credentials(**body) return output @@ -4272,14 +4571,34 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body @@ -4322,22 +4641,23 @@ def test_delete_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_credentials(**body) return output @@ -4365,6 +4685,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_gateways #----------------------------------------------------------------------------- @@ -4404,22 +4725,23 @@ def test_list_gateways_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_gateways(**body) return output @@ -4474,22 +4796,23 @@ def test_create_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format( + body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_gateway(**body) return output @@ -4497,7 +4820,9 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", }) + body.update({ + "name": "string1", + }) return body def construct_required_body(self): @@ -4545,22 +4870,23 @@ def test_get_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format( + body['environment_id'], body['gateway_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_gateway(**body) return output @@ -4617,22 +4943,23 @@ def test_delete_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format( + body['environment_id'], body['gateway_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_gateway(**body) return output @@ -4672,6 +4999,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -4688,6 +5016,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -4699,6 +5028,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -4715,6 +5045,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index fedc9e9bd..0276527c2 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_collections #----------------------------------------------------------------------------- @@ -61,7 +62,8 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, + fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -75,16 +77,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -110,6 +112,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -155,16 +158,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -172,7 +175,39 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) + body.update({ + "collection_ids": [], + "filter": + "string1", + "query": + "string1", + "natural_language_query": + "string1", + "aggregation": + "string1", + "count": + 12345, + "return_": [], + "offset": + 12345, + "sort": + "string1", + "highlight": + True, + "spelling_suggestions": + True, + "table_results": + QueryLargeTableResults._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "suggested_refinements": + QueryLargeSuggestedRefinements._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "passages": + QueryLargePassages._from_dict( + json.loads( + """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" + )), + }) return body def construct_required_body(self): @@ -226,16 +261,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -287,7 +322,8 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -301,16 +337,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -376,16 +412,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -412,6 +448,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for get_component_settings #----------------------------------------------------------------------------- @@ -443,7 +480,8 @@ def test_get_component_settings_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_component_settings_empty(self): - check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) + check_empty_required_params( + self, fake_response_ComponentSettingsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -451,22 +489,23 @@ def test_get_component_settings_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format(body['project_id']) + endpoint = '/v2/projects/{0}/component_settings'.format( + body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -492,6 +531,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -531,22 +571,23 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( + body['project_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -608,22 +649,23 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -679,7 +721,8 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, + fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -687,22 +730,23 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -733,6 +777,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_training_queries #----------------------------------------------------------------------------- @@ -772,22 +817,23 @@ def test_list_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -842,22 +888,23 @@ def test_delete_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -912,22 +959,23 @@ def test_create_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -935,13 +983,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body @@ -984,22 +1040,23 @@ def test_get_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1056,22 +1113,23 @@ def test_update_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1080,14 +1138,22 @@ def construct_full_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body @@ -1113,6 +1179,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1129,6 +1196,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1140,6 +1208,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1156,6 +1225,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 54f08512e..2a8a15d89 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for translate #----------------------------------------------------------------------------- @@ -75,28 +76,38 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate(**body) return output def construct_full_body(self): body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + body.update({ + "text": [], + "model_id": "string1", + "source": "string1", + "target": "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + body.update({ + "text": [], + "model_id": "string1", + "source": "string1", + "target": "string1", + }) return body @@ -110,6 +121,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_identifiable_languages #----------------------------------------------------------------------------- @@ -154,16 +166,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_identifiable_languages(**body) return output @@ -208,7 +220,8 @@ def test_identify_required_response(self): #-------------------------------------------------------- @responses.activate def test_identify_empty(self): - check_empty_required_params(self, fake_response_IdentifiedLanguages_json) + check_empty_required_params(self, + fake_response_IdentifiedLanguages_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -222,16 +235,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.identify(**body) return output @@ -257,6 +270,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_models #----------------------------------------------------------------------------- @@ -301,16 +315,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_models(**body) return output @@ -372,16 +386,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.create_model(**body) return output @@ -445,16 +459,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_model(**body) return output @@ -515,16 +529,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_model(**body) return output @@ -550,6 +564,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_documents #----------------------------------------------------------------------------- @@ -594,16 +609,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_documents(**body) return output @@ -662,16 +677,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate_document(**body) return output @@ -738,16 +753,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -808,16 +823,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -872,22 +887,23 @@ def test_get_translated_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v3/documents/{0}/translated_document'.format(body['document_id']) + endpoint = '/v3/documents/{0}/translated_document'.format( + body['document_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_translated_document(**body) return output @@ -926,6 +942,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -942,6 +959,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -953,6 +971,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -969,6 +988,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_natural_language_understanding.py b/test/unit/test_natural_language_understanding.py deleted file mode 100644 index d5b01db4c..000000000 --- a/test/unit/test_natural_language_understanding.py +++ /dev/null @@ -1,146 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -from ibm_watson import NaturalLanguageUnderstandingV1 -from ibm_watson.natural_language_understanding_v1 import \ - Features, ConceptsOptions, EntitiesOptions, KeywordsOptions, CategoriesOptions, \ - EmotionOptions, MetadataOptions, SemanticRolesOptions, RelationsOptions, \ - SentimentOptions -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -import os -import pytest -import responses - - -base_url = 'https://gateway.watsonplatform.net' -default_url = '{0}/natural-language-understanding/api'.format(base_url) - - -class TestFeatures(TestCase): - def test_concepts(self): - c = Features(concepts=ConceptsOptions()) - assert c._to_dict() == {'concepts': {}} - c = Features(concepts=ConceptsOptions(limit=10)) - assert c._to_dict() == {'concepts': {'limit': 10}} - - def test_entities(self): - e = Features(entities=EntitiesOptions()) - assert e._to_dict() == {'entities': {}} - - def test_keywords(self): - k = Features(keywords=KeywordsOptions()) - assert k._to_dict() == {'keywords': {}} - - def test_categories(self): - c = Features(categories=CategoriesOptions()) - assert c._to_dict() == {'categories': {}} - - def test_emotion(self): - e = Features(emotion=EmotionOptions()) - assert e._to_dict() == {'emotion': {}} - - def test_metadata(self): - m = Features(metadata=MetadataOptions()) - assert m._to_dict() == {'metadata': {}} - - def test_semantic_roles(self): - s = Features(semantic_roles=SemanticRolesOptions()) - assert s._to_dict() == {'semantic_roles': {}} - - def test_relations(self): - r = Features(relations=RelationsOptions()) - assert r._to_dict() == {'relations': {}} - - def test_sentiment(self): - s = Features(sentiment=SentimentOptions()) - assert s._to_dict() == {'sentiment': {}} - - -class TestNaturalLanguageUnderstanding(TestCase): - def test_version_date(self): - with pytest.raises(TypeError): - NaturalLanguageUnderstandingV1() # pylint: disable=E1120 - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - assert nlu - - @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is not None, - reason='credentials may come from VCAP_SERVICES') - def test_missing_credentials(self): - with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23') - with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23') - - def test_analyze_throws(self): - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - with pytest.raises(ValueError): - nlu.analyze(None, text="this will not work") - - @responses.activate - def test_text_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions()), text="hello this is a test") - assert len(responses.calls) == 1 - - @responses.activate - def test_html_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions(), - emotion=EmotionOptions(document=False)), - html="hello this is a test") - assert len(responses.calls) == 1 - - @responses.activate - def test_url_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions(), - emotion=EmotionOptions(document=False)), - url="http://cnn.com", - xpath="/bogus/xpath", language="en") - assert len(responses.calls) == 1 - - @responses.activate - def test_list_models(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models" - responses.add(responses.GET, nlu_url, status=200, - body="{\"resulting_key\": true}", - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.list_models() - assert len(responses.calls) == 1 - - @responses.activate - def test_delete_model(self): - model_id = "invalid_model_id" - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models/" + model_id - responses.add(responses.DELETE, nlu_url, status=200, - body="{}", content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.delete_model(model_id) - assert len(responses.calls) == 1 From 7960f62ae8ab0c517902e822c713e9aae5d07048 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 19:01:55 -0500 Subject: [PATCH 23/28] chore(all): Manually remove unused imports --- ibm_watson/assistant_v1.py | 2 -- ibm_watson/assistant_v2.py | 2 -- ibm_watson/compare_comply_v1.py | 4 ---- ibm_watson/discovery_v1.py | 3 --- ibm_watson/discovery_v2.py | 3 --- ibm_watson/language_translator_v3.py | 3 --- ibm_watson/natural_language_classifier_v1.py | 4 ---- ibm_watson/natural_language_understanding_v1.py | 3 --- ibm_watson/personality_insights_v3.py | 2 -- ibm_watson/speech_to_text_v1.py | 4 ---- ibm_watson/text_to_speech_v1.py | 3 --- ibm_watson/tone_analyzer_v3.py | 2 -- ibm_watson/visual_recognition_v3.py | 3 --- ibm_watson/visual_recognition_v4.py | 4 ---- 14 files changed, 42 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 393be33e2..b48cd04da 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -29,8 +29,6 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 60b838104..dd10f4d60 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -27,8 +27,6 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 9266c3ffa..c7ef88c6f 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -27,13 +27,9 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index f57693456..a0a7b5db6 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -30,13 +30,10 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO import sys ############################################################################## diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 0af5456bd..ffc9563a3 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -29,13 +29,10 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO import sys ############################################################################## diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 39c70bf37..defddcbcd 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -29,13 +29,10 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 2b7ffd4a6..a32357a57 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -28,13 +28,9 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 8fb571cee..f3d22e304 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -32,9 +32,6 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import Dict from typing import List diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 2f99e5075..afa52b76f 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -39,8 +39,6 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index b3be2d348..601f7fa12 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -40,13 +40,9 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 371bdf07f..e09c5fb00 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -36,9 +36,6 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import Dict from typing import List diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 42287778f..608e4561e 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -31,8 +31,6 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 6d0986b7b..c1d117c7f 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -27,13 +27,10 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 8139a7a69..4ad597ff2 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -26,13 +26,9 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from ibm_cloud_sdk_core import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import BinaryIO from typing import Dict from typing import List -from typing import TextIO ############################################################################## # Service From ca3132c1e0d9709b51694b5405db60d47dc88c10 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 15 Jan 2020 12:53:04 -0500 Subject: [PATCH 24/28] chore(travis): update travis integration test values --- .env.enc | Bin 1792 -> 2112 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 314487b935a79d4c97b851c97835575d10fd900b..612fb7711487b21a9837e7382aaf4a83fabb0c27 100644 GIT binary patch literal 2112 zcmV-G2*39u_@t;Rprm1?I~j9`+L;k4$}#SPn%PgDyF$A75#!7>d1uWuiXn(_#rhthQdf1-u(GNZvfitv+zkfhNN3hejQ$!- z*l@hcaX7G)HMvzF)BW}4bReyG-Kt)!C_}iT=$E{(fskbYhmV!}t2}G_5J*e5RnGNP zUZ^k{vY>71Z&OvxAMM8)gYkJjR50AMmd~`r#<|})7e2yYp;>V%<)xmmchUe(Tv77X z2iCPcNX`R{eF2Gc*<5V|&Crq)h3De53orF{Dx<%5RR@6k2NtbF#e7LKurIE>Tpsw} zT*$qa?v8Drl6t{ZhO{$2F&IZ}waL;(2R=9JQrIE5cwRUbScmI2phV+yZ0{$4Cgwf1 zud7+7fG=Zu9Q6Uf1by3K9Rlac%QvH2{4<@&=vR{OSM8C}J`=)|;?o(z??FA;pSPei zP@(UnUu@T@&x_oB{U;6?v=^%gE_jJPCRH^Mb5oWh;L}gG7bk%1j4GQzW7nk!DpHJ> zksbE`odgerxs*F1Nln_di`7esJ`A3z+IZ=awo}PSVB2)>-ZCGkB`jUdXJ%!}S};=2 zp|`o*u0S)xm2$XgeS>MM+yYab$|3_+kX_jxGNRO&Tlgr3AmJ0AW*;JP{x8#%Gk9ch zan!+kBUG`%1dh(Qh%I5}#2etQl?l{2oniIy&BavE%Zp!Vet=Iip1yO?bMWQkF!H03 zGhO_J?gc>Chbm zBaU=zn^~{(dIg5$iSg~}oFwr>JK!wGS52F-F?k@K2G{Q^UnINUn5(E*+z&)`Q7leL_{m5V%NhT zMB4-4Jvz%*+e^Xw3&Cj7Kjb9Wi`g3aZt;HF^pPz&scu??I+5>|T$ZRkBD^c8TZnXr zlf7Z;L`WKO@ewAyKGG@qNKaS<;O~uwl(SRuiKSq__T+fxfmQVx0;$MN=(GsAnC!ga z{!vEu(0I@c^Y9Ic3y+u-?HV4YF{5su@Ffq&;tR*B;p1%;A>L7e=t3kL^6y3)Ss^O= zmrAUey9-Z)`JZ%vG&Ut%zmGKd$&4%~LiTeLZd=Y&LgNFCG<@6414mixPyIe1GN*5< z(g1Tx37z-vViXh;14sa@cEmV5_N%(bqln%%o)+#8?#o7x4-|HWv6we0?ZAHTjt3?H zR;J|v0#gw(^3xiuPVqz*m8hu|@hb!hoAp-sG-F@jO`MHlf;s6-Jv{h7eL+Z!<#>I- zY1nIb1|EDey-O|&H|skc13L~#mw&W*gXKPh<#JK==x=b!uhi)EKABzOF1|D((zi$9De zhvriDee((nO{3cQh7vz*?2bD3(Cv^KFA6EeLdusV-jX|my71Xz)&yIrG;hNAGQ&cj z^CId#xJ&Vhxn}NU9d0E!zB^BK;8|s4>m+$0&O8(Z@7OmADm2 z279$oRG^tP8TyHt6G6XqNd5wE2*Nta2iLQUSPZMpRMG-}PC~l~8L_ZK(T+)mBORY9 zD_t(IEJ`z5(Zkys6j{}v-TQMBa&VzFJrDT_rIv;v?isn|v+&uG(C#+fImPLoagx05 zOkk~RllFLxos9=T3~oTQ{f+8VU}v=Jtsy~hjLH`m@I*t6GP}V0`48n$*av#Nq3VD0 zc-6h$hfWQQEbHoAa57_p9GJEg5tZ6%<%1KTVot7ueFcQa?UW=db&?5-bJQU*4IdKD zSw|WM!gzeP;7OmYLOjj(k$n*2@XbiQSiY80cn~KR5UVG}+BF;5rN@2(l2Q6Zx=t_jGGi&Mq!BD38;}zBsFCdTfeGl;WGmwV zM2JvTTqamHW12J_UdN_T)y)GiA{@Q&J+&ux5qk>B308qpdn~t z(}sBHxiBg_;DgOS50xXTrn5~M_JwQ+hCqJa@6>@;70t+4%~5Sd*9Vc;;=eRO2F@3_ qHi8gvW~n#{^Q2aHvUHqNk&c5&7OdtpRDX(O<+&!J@t%Sg(ArvkIT)Y- literal 1792 zcmV+b2mkofCg_VMQQ-b2GupQ4;73}wQ=Z1`5iUqv)8<{whT{GvuJ7TtG!dRJz(Pi$ z#RF$f7H~>ZLaqh zMbzR&zFcCMUvGVJ~VcU=d0NkSPhB_Zb(nQcjEvMdr(xAo4#5aNyyJx+(^8z_D)d~5n0 zozTG@-py9nZ^B!glYX7=0-0I{1E+#Yo*DdUzPG|6F?tm+ttJi_O0)OT(32~znGN>= zc1<6?$u>rIh!O4gc7R+NRu% z!{=PBRgvV~T`LNFN*3^M38lI384JDxt;jKGPJUvvTt`WHcv_MwCj@V1IcVFpe z*u(Nm<^#Sbafs%RQTk0?^xPLYGWc{l+_x5Jq=?Pc0ZPdx?+ zUW+TTzb-1h3kC)L{k@vNhEaH`TsqGs6O(H;o~>gOoMuaJSx6K8C_=yif2JNg-^hC+ z-&*%p)4N!CnE~Y`qX&}=$8JiLb*Gq}SRerD{gN<=xeY>Ekwl*owPA6bn~@XU(L~!2 z1%K)BV>g0LvNb%j=RuvJA2P1hkV8JhZE=B-q*_4#HR4R)j_o1>9Un!;Q-cT87(>B5 zVg7tG?l_9jgu=5Tu~$(L`6?nKe4CN;zWCGJAh3)9s~B7 z=lnv-t&PI;>G|XeGj<-}-c+tF)1ef~xG!&@rPz5<^U8^uQ?|%6!9O@*=2zS^GK@#s z-`4RFeP5#Wiwv@p9pl-D@~6ULFf^kD#qvCfxD6l)&}HSKz)hX&IE$pqGd4zRbcX^> zWZtF4z{xYk0J=1y`ZGu#K49^HGAGZTfBSFc7BNj)AYKn2rAo1v1ZlCh7(|4nFbXNWdci32ERulOZ`<)LK&tWikaaKZUm&}91(l> z_^O2YxIQ0?j?eM!lGSx&3Sv>&taT`X=UZg}vkzzGkeRW6Yb3DZhF z;u0;8{OGR$4m#0KDNfm_Y&rBd#96^4xQc_(4EgRD6h{-7LUX5PX90Tl>-CO&B%@~J z@tAHEy#Qn_y)#}fzi5Ea2ThY6oH%mEVW5r$+5?889$+52O-p#IsYTn=DG!7rp_M0h z#F*I>7C783^g_a9@=Zd!j&K;OF0mWseWr}guf*Lws&&?XKv+XG_I~ya>H3eg!u!%Q z+^~+^4n;Z2^pQ{A8){eh+)4Im7)5_Z0jDTamTKsN8qx2^(xI2chN8||Mo*GLCg)t4 iDd=ohlcEt-zm3{#0D5ai*Twu1StE2IF^TgT0OyHb#C(SU From 4bd210197d92d7bc82a809093647b82da08f24a5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 16 Jan 2020 13:49:07 -0500 Subject: [PATCH 25/28] chore(copyright): correct copyright year --- ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 2 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 2 +- ibm_watson/discovery_v2.py | 2 +- ibm_watson/language_translator_v3.py | 2 +- ibm_watson/natural_language_classifier_v1.py | 2 +- ibm_watson/natural_language_understanding_v1.py | 2 +- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/speech_to_text_v1_adapter.py | 2 +- ibm_watson/text_to_speech_v1.py | 2 +- ibm_watson/tone_analyzer_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- setup.py | 2 +- test/unit/test_assistant_v1.py | 2 +- test/unit/test_assistant_v2.py | 2 +- test/unit/test_common.py | 2 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- test/unit/test_natural_language_classifier_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 2 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- test/unit/test_visual_recognition_v4.py | 2 +- 30 files changed, 30 insertions(+), 30 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b48cd04da..b03b97e85 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index dd10f4d60..c3384fb0e 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index c7ef88c6f..df8283d41 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index a0a7b5db6..c06230534 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index ffc9563a3..4b23c8d5b 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index defddcbcd..d899c478e 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. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index a32357a57..632f2a28a 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index f3d22e304..60948e696 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. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index afa52b76f..37c29ba51 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 601f7fa12..70b37757e 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. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index c813b5370..3585eefb6 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index e09c5fb00..08edf24c8 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. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 608e4561e..0aed13498 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index c1d117c7f..77964b699 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 4ad597ff2..22294f14f 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/setup.py b/setup.py index 8e949081a..392c4fd66 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 59237d056..8dfa617fe 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. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 0c2cb1abd..8755ee6d5 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. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_common.py b/test/unit/test_common.py index 110f26259..62e0bbf6b 100644 --- a/test/unit/test_common.py +++ b/test/unit/test_common.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2019 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 171458bd1..7b54f1773 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 363c5d6e9..07c5b3914 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. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 0276527c2..12cdef354 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. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 2a8a15d89..f0a4f3098 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. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index d02f9bbc8..105fe8264 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 9fae31cba..22cab9e9f 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index c3a534087..1cb6cf5b3 100755 --- 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. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 2d8efd6f1..8cc3a8c83 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. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 8ff7cb6c4..d9db2185d 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 9aecb805e..fb2b7d779 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 1a76c2d4e..0c06d3194 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 8bbc0ed3194d28cc4d0bd32b513988896c65087e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 16 Jan 2020 15:05:14 -0500 Subject: [PATCH 26/28] chore(servicename): Manual changes to service name --- .env.enc | Bin 2112 -> 1792 bytes ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 2 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- 6 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.env.enc b/.env.enc index 612fb7711487b21a9837e7382aaf4a83fabb0c27..2ce119a8345c896d40fa79e8c11cbb3240481f78 100644 GIT binary patch literal 1792 zcmV+b2mknBubJpO&gX#hB52B27T>;ohes7tHO9E1FskTFm@Pz31VtUp+Kl$uwplq0 zva)YFyTM{koP@8B;tO4(gEzq<0kEu zOZTN~*X*y5Y7t!74bjONP++|0lh`BCnrNSV-E3Lz(c7aMc0GNo$}`sv&7_HEt}O>{ zV$+avXO*d&{_GxV|2vK&4pKpbsoEE+ueuZ8+FpE}Wq>v|5KN7KSC4eje1q-R=d5E5 zrphd+hL?Rmx=jlP$h@r_hf|_5q@dZXLSMuTu7a%;}v1C>kPclo9_5{jVcKO^BZbT zl|#?s42%1^O)+m;K2?yrJOx>(=Lj-PR%=1zYM~5S3u7;l|1~ScaKu4WNIFjVMI-Qc zjL2|O{d0auj0ATQWi;6}=_`$XhHQ)aHSbN~@gaZF-=*;ygI<8QjB@7jz89T?oDhyu z`Q^aaN2i-fph@=N2a5nYF6z@4G6SucV+C(!N8?<-VgD{NX@+5OXc%rv+bcPQB4%NW z##82S4U^u3IQ;G$EySQBVV<5LSFlF!48n^wBH@u!aVe+7+O*hH8+{?hKP-1K^*Kb> z8AZpuq2W;xM%~sa*Eq-tVWA;~MAJM$Peu{bu?(pLq}N-ecIq5Um3~W#RHAso6bXhF zd;sze_5hg>3cEZjU`RQ-Uzz#x52Z(gsEdMZ@eko)fsd99f8jZ`{Ae^7ugsec>!iUugupbnb z1_IgdxlBW_`HJIJD)FGAW7_eTU!s^hAO_daG8e#OyXY)?(N$D}j6qHN1AxV@430vA zI_s1^pyx4*(8h`7^Q`7xk#3(14NkoS3@t<;4F}9kC7l#@?Iv_XxjN>8xnngqF;MUd zDUFBTS+YnXqg5nlye@9^7E``~x#p4d1!gIcldYBUEQV=!uz$!N+wgvj1s*lF?JG<* z_Lrj!u*0VB${tE{_+sdk4@Q7nDISw-ci3^Cry>n+j3LntUYu$304`}+Yq0H~jbB|r zCXo9lN z%CWFlISUZp>$0WMPRi~GgVfvNiKOAfOK> z;66VOdCg}wRu0jLT4YZs{H}C{uNY1gYs#Y>0(q=q4Y5-_^8UJzkYbP__p38=B`H_g zrQFZV8t6W50eXon``(2uu||o{107qp+F(J5a`#4s3Pk_-+%?^RO_gFOR_xz5$QUmZ z)A--qIar_?2hh0jcEI&^b2WBHSYk}FXO&2gy}m#(?kDEk>Snc_ck0ZW)z9s3fRG?l zeERqr=HW8n0@(|ZBQy@K=w`G8Y*hxo;C&vxlJXQf&}rqEBv$}RMfIr|t*`NR%Zq4y zNTRnhLL@z%$I6J=@eADc=g>K4aOWU8fI}{x`epg?28_FztN#Xah$N_ELN%1oKHW2;n;uu3LdtXKES${DIBx6IIC%xYmnrrRuejP{*1fL@^Mg6)&)q=UnTugS{SLvUe*&XsX(2Q&U{`@j0wfDjGDdmS5 z$70)GE6NAIS$hG`aogy^lrI@-9XMS;F{=-FSk~qkR*Ry7jBkw+&9FWVL%qMXHj4D> zVI*Dl!j?q|t6OAo>?j%zB*e35(;Z+iM?&|Ime^_vLp?{>4=|?px*wZ`N@+c@aj{mY iZJh-Es-ot;5e-hJ!OnC$3bsem0n4d1uWuiXn(_#rhthQdf1-u(GNZvfitv+zkfhNN3hejQ$!- z*l@hcaX7G)HMvzF)BW}4bReyG-Kt)!C_}iT=$E{(fskbYhmV!}t2}G_5J*e5RnGNP zUZ^k{vY>71Z&OvxAMM8)gYkJjR50AMmd~`r#<|})7e2yYp;>V%<)xmmchUe(Tv77X z2iCPcNX`R{eF2Gc*<5V|&Crq)h3De53orF{Dx<%5RR@6k2NtbF#e7LKurIE>Tpsw} zT*$qa?v8Drl6t{ZhO{$2F&IZ}waL;(2R=9JQrIE5cwRUbScmI2phV+yZ0{$4Cgwf1 zud7+7fG=Zu9Q6Uf1by3K9Rlac%QvH2{4<@&=vR{OSM8C}J`=)|;?o(z??FA;pSPei zP@(UnUu@T@&x_oB{U;6?v=^%gE_jJPCRH^Mb5oWh;L}gG7bk%1j4GQzW7nk!DpHJ> zksbE`odgerxs*F1Nln_di`7esJ`A3z+IZ=awo}PSVB2)>-ZCGkB`jUdXJ%!}S};=2 zp|`o*u0S)xm2$XgeS>MM+yYab$|3_+kX_jxGNRO&Tlgr3AmJ0AW*;JP{x8#%Gk9ch zan!+kBUG`%1dh(Qh%I5}#2etQl?l{2oniIy&BavE%Zp!Vet=Iip1yO?bMWQkF!H03 zGhO_J?gc>Chbm zBaU=zn^~{(dIg5$iSg~}oFwr>JK!wGS52F-F?k@K2G{Q^UnINUn5(E*+z&)`Q7leL_{m5V%NhT zMB4-4Jvz%*+e^Xw3&Cj7Kjb9Wi`g3aZt;HF^pPz&scu??I+5>|T$ZRkBD^c8TZnXr zlf7Z;L`WKO@ewAyKGG@qNKaS<;O~uwl(SRuiKSq__T+fxfmQVx0;$MN=(GsAnC!ga z{!vEu(0I@c^Y9Ic3y+u-?HV4YF{5su@Ffq&;tR*B;p1%;A>L7e=t3kL^6y3)Ss^O= zmrAUey9-Z)`JZ%vG&Ut%zmGKd$&4%~LiTeLZd=Y&LgNFCG<@6414mixPyIe1GN*5< z(g1Tx37z-vViXh;14sa@cEmV5_N%(bqln%%o)+#8?#o7x4-|HWv6we0?ZAHTjt3?H zR;J|v0#gw(^3xiuPVqz*m8hu|@hb!hoAp-sG-F@jO`MHlf;s6-Jv{h7eL+Z!<#>I- zY1nIb1|EDey-O|&H|skc13L~#mw&W*gXKPh<#JK==x=b!uhi)EKABzOF1|D((zi$9De zhvriDee((nO{3cQh7vz*?2bD3(Cv^KFA6EeLdusV-jX|my71Xz)&yIrG;hNAGQ&cj z^CId#xJ&Vhxn}NU9d0E!zB^BK;8|s4>m+$0&O8(Z@7OmADm2 z279$oRG^tP8TyHt6G6XqNd5wE2*Nta2iLQUSPZMpRMG-}PC~l~8L_ZK(T+)mBORY9 zD_t(IEJ`z5(Zkys6j{}v-TQMBa&VzFJrDT_rIv;v?isn|v+&uG(C#+fImPLoagx05 zOkk~RllFLxos9=T3~oTQ{f+8VU}v=Jtsy~hjLH`m@I*t6GP}V0`48n$*av#Nq3VD0 zc-6h$hfWQQEbHoAa57_p9GJEg5tZ6%<%1KTVot7ueFcQa?UW=db&?5-bJQU*4IdKD zSw|WM!gzeP;7OmYLOjj(k$n*2@XbiQSiY80cn~KR5UVG}+BF;5rN@2(l2Q6Zx=t_jGGi&Mq!BD38;}zBsFCdTfeGl;WGmwV zM2JvTTqamHW12J_UdN_T)y)GiA{@Q&J+&ux5qk>B308qpdn~t z(}sBHxiBg_;DgOS50xXTrn5~M_JwQ+hCqJa@6>@;70t+4%~5Sd*9Vc;;=eRO2F@3_ qHi8gvW~n#{^Q2aHvUHqNk&c5&7OdtpRDX(O<+&!J@t%Sg(ArvkIT)Y- diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b03b97e85..42a0b126c 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -41,7 +41,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index c3384fb0e..11157bbac 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -39,7 +39,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index df8283d41..01339bdbd 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -40,7 +40,7 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' - DEFAULT_SERVICE_NAME = 'compare-comply' + DEFAULT_SERVICE_NAME = 'compare_comply' def __init__( self, diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 77964b699..9428e5ab8 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -41,7 +41,7 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' - DEFAULT_SERVICE_NAME = 'watson_vision_combined' + DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( self, diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 22294f14f..cdabfac4c 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -39,7 +39,7 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' - DEFAULT_SERVICE_NAME = 'watson_vision_combined' + DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( self, From 0d09c8f52632652c07703388652c60c4a1d42733 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 16 Jan 2020 22:35:47 +0000 Subject: [PATCH 27/28] =?UTF-8?q?Bump=20version:=204.1.0=20=E2=86=92=204.2?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 0951758da..6ac62c5dc 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.1.0 +current_version = 4.2.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index fa721b497..ea5d65fc7 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.1.0' +__version__ = '4.2.0' diff --git a/setup.py b/setup.py index 392c4fd66..91f4987c3 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.1.0' +__version__ = '4.2.0' if sys.argv[-1] == 'publish': From d5ae0704ab5c8e4ebb9a2fd2f4258b4d492281ff Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 16 Jan 2020 22:35:47 +0000 Subject: [PATCH 28/28] chore(release): 4.2.0 release notes # [4.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.1.0...v4.2.0) (2020-01-16) ### Features * **core:** Update core version ([88106fb](https://github.com/watson-developer-cloud/python-sdk/commit/88106fb9c9460e60363a814565b51a512805f8b9)) * **stt:** New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` ([776dc86](https://github.com/watson-developer-cloud/python-sdk/commit/776dc8635a98489a9ceb8abf155947bb0f39ad8a)) * **stt:** New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket ([040946f](https://github.com/watson-developer-cloud/python-sdk/commit/040946f88d6b652f8b8e5638429b69fb1035e79a)) --- CHANGELOG.md | 9 +++ package-lock.json | 171 +++++++++++++++++----------------------------- 2 files changed, 70 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c425f246..292541a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +# [4.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.1.0...v4.2.0) (2020-01-16) + + +### Features + +* **core:** Update core version ([88106fb](https://github.com/watson-developer-cloud/python-sdk/commit/88106fb9c9460e60363a814565b51a512805f8b9)) +* **stt:** New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` ([776dc86](https://github.com/watson-developer-cloud/python-sdk/commit/776dc8635a98489a9ceb8abf155947bb0f39ad8a)) +* **stt:** New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket ([040946f](https://github.com/watson-developer-cloud/python-sdk/commit/040946f88d6b652f8b8e5638429b69fb1035e79a)) + # [4.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.4...v4.1.0) (2019-11-27) diff --git a/package-lock.json b/package-lock.json index 3603f0197..6dfeb67ad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,17 +3,17 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.5.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", - "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", "requires": { - "@babel/highlight": "^7.0.0" + "@babel/highlight": "^7.8.3" } }, "@babel/highlight": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.5.0.tgz", - "integrity": "sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", + "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", "requires": { "chalk": "^2.0.0", "esutils": "^2.0.2", @@ -79,9 +79,9 @@ } }, "@octokit/rest": { - "version": "16.35.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.35.0.tgz", - "integrity": "sha512-9ShFqYWo0CLoGYhA1FdtdykJuMzS/9H6vSbbQWDX4pWr4p9v+15MsH/wpd/3fIU+tSxylaNO48+PIHqOkBRx3w==", + "version": "16.36.0", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.36.0.tgz", + "integrity": "sha512-zoZj7Ya4vWBK4fjTwK2Cnmu7XBB1p9ygSvTk2TthN6DVJXM4hQZQoAiknWFLJWSTix4dnA3vuHtjPZbExYoCZA==", "requires": { "@octokit/request": "^5.2.0", "@octokit/request-error": "^1.0.2", @@ -122,39 +122,37 @@ "integrity": "sha512-9Tj/qn+y2j+sjCI3Jd+qseGtHjOAeg7dU2/lVcqIQ9TV3QDaDXDYXcoOHU+7o2Hwh8L8ymL4gfuO7KxDs3q2zg==" }, "@semantic-release/exec": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-3.3.8.tgz", - "integrity": "sha512-GH1v5BwXRIUAnvrXjil+R+9DjI+ELgk2NMdQUAnp2/qZ6YItZt6KI8HrY3zAFDrG0YGaOwC9XxuUNKeldsOK7A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-4.0.0.tgz", + "integrity": "sha512-cOvPeWllHaTkwA0Y/Ffskrc1Fcu2VB5YmOYGfDmznTtUIPMk42UuwqsNVYwQPBsHYIggOFkjlnXvInZsGzEe2Q==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", "debug": "^4.0.0", - "execa": "^3.2.0", + "execa": "^4.0.0", "lodash": "^4.17.4", "parse-json": "^5.0.0" } }, "@semantic-release/git": { - "version": "7.0.18", - "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-7.0.18.tgz", - "integrity": "sha512-VwnsGUXpNdvPcsq05BQyLBZxGUlEiJCMKNi8ttLvZZAhjI1mAp9dwypOeyxSJ5eFQ+iGMBLdoKF1LL0pmA/d0A==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-8.0.0.tgz", + "integrity": "sha512-CfjEXtxd4zmhAPtPfrerHQi5QkdMzDhoZY7bUi4zjz3S6PaAlJrpAt09/iV+JKmePEJWiWFla/+a0Y9Qull7YQ==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", "debug": "^4.0.0", "dir-glob": "^3.0.0", - "execa": "^3.2.0", - "fs-extra": "^8.0.0", - "globby": "^10.0.0", + "execa": "^4.0.0", "lodash": "^4.17.4", "micromatch": "^4.0.0", "p-reduce": "^2.0.0" } }, "@semantic-release/github": { - "version": "5.5.5", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-5.5.5.tgz", - "integrity": "sha512-Wo9OIULMRydbq+HpFh9yiLvra1XyEULPro9Tp4T5MQJ0WZyAQ3YQm74IdT8Pe/UmVDq2nfpT1oHrWkwOc4loHg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-6.0.1.tgz", + "integrity": "sha512-4/xMKFe7svbv5ltvBxoqPY8fBSPyllVtnf2RMHaddeRKC8C/7FqakwRDmui7jgC3alVrVsRtz/jdTdZjB4J28Q==", "requires": { "@octokit/rest": "^16.27.0", "@semantic-release/error": "^2.2.0", @@ -164,9 +162,9 @@ "dir-glob": "^3.0.0", "fs-extra": "^8.0.0", "globby": "^10.0.0", - "http-proxy-agent": "^2.1.0", - "https-proxy-agent": "^3.0.0", - "issue-parser": "^5.0.0", + "http-proxy-agent": "^3.0.0", + "https-proxy-agent": "^4.0.0", + "issue-parser": "^6.0.0", "lodash": "^4.17.4", "mime": "^2.4.3", "p-filter": "^2.0.0", @@ -195,9 +193,9 @@ "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" }, "@types/node": { - "version": "12.12.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.14.tgz", - "integrity": "sha512-u/SJDyXwuihpwjXy7hOOghagLEV1KdAST6syfnOk6QZAMzZuWZqXy5aYYZbh8Jdpd4escVFP0MvftHNDb9pruA==" + "version": "13.1.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.7.tgz", + "integrity": "sha512-HU0q9GXazqiKwviVxg9SI/+t/nAsGkvLDkIdxz+ObejG2nX6Si00TeLqHMoS+a/1tjH7a8YpKVQwtgHuMQsldg==" }, "@types/retry": { "version": "0.12.0", @@ -205,12 +203,9 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" }, "agent-base": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.3.0.tgz", - "integrity": "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==", - "requires": { - "es6-promisify": "^5.0.0" - } + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-5.1.1.tgz", + "integrity": "sha512-TMeqbNl2fMW0nMjTEPOwe3J/PRFP4vqeoNuQMG0HlMrtm5QxKqdvAkZ1pRBQ/ulIyDD5Yq0nJ7YbdD8ey0TO3g==" }, "aggregate-error": { "version": "3.0.1", @@ -356,19 +351,6 @@ "is-arrayish": "^0.2.1" } }, - "es6-promise": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", - "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" - }, - "es6-promisify": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", - "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", - "requires": { - "es6-promise": "^4.0.3" - } - }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -380,9 +362,9 @@ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "execa": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz", - "integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.0.tgz", + "integrity": "sha512-JbDUxwV3BoT5ZVXQrSVbAiaXhXUkIwvbhPIwZ0N13kX+5yCzOhUNdocxB/UQRuYOHRYYwAxKYwJYc0T4D12pDA==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -391,15 +373,14 @@ "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", - "p-finally": "^2.0.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" } }, "fast-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.0.tgz", - "integrity": "sha512-TrUz3THiq2Vy3bjfQUB2wNyPdGBeGmdjbzzBLhfHN4YFurYptCKwGq/TfiRavbGywFRzY6U2CdmQ1zmsY5yYaw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.1.tgz", + "integrity": "sha512-nTCREpBY8w8r+boyFYAx21iL6faSsQynliPHM4Uf56SbkyohCNxpVPEH9xrF5TXKy+IsjkPUHDKiUkzBVRXn9g==", "requires": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -469,9 +450,9 @@ } }, "globby": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz", - "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.2.tgz", + "integrity": "sha512-7dUi7RvCoT/xast/o/dLN53oqND4yk0nsHkhRgn9w65C4PofCLOoJ39iSOg+qVDdWQPIEj+eszMHQ+aLVwwQSg==", "requires": { "@types/glob": "^7.1.1", "array-union": "^2.1.0", @@ -494,46 +475,21 @@ "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "http-proxy-agent": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz", - "integrity": "sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-3.0.0.tgz", + "integrity": "sha512-uGuJaBWQWDQCJI5ip0d/VTYZW0nRrlLWXA4A7P1jrsa+f77rW2yXz315oBt6zGCF6l8C2tlMxY7ffULCj+5FhA==", "requires": { - "agent-base": "4", - "debug": "3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - } + "agent-base": "5", + "debug": "4" } }, "https-proxy-agent": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz", - "integrity": "sha512-+ML2Rbh6DAuee7d07tYGEKOEi2voWPUGan+ExdPbPW6Z3svq+JCqr0v8WmKPOkz1vOVykPCBSuobe7G8GJUtVg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-4.0.0.tgz", + "integrity": "sha512-zoDhWrkR3of1l9QAL8/scJZyLu8j/gBkcwcaQOZh7Gyh/+uJQzGVETdgT30akuwkpL8HTRfssqI3BZuV18teDg==", "requires": { - "agent-base": "^4.3.0", - "debug": "^3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "requires": { - "ms": "^2.1.1" - } - } + "agent-base": "5", + "debug": "4" } }, "human-signals": { @@ -612,9 +568,9 @@ "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==" }, "issue-parser": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-5.0.0.tgz", - "integrity": "sha512-q/16W7EPHRL0FKVz9NU++TUsoygXGj6JOi88oulyAcQG+IEZ0T6teVdE+VLbe19OfL/tbV8Wi3Dfo0HedeHW0Q==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-6.0.0.tgz", + "integrity": "sha512-zKa/Dxq2lGsBIXQ7CUZWTHfvxPC2ej0KfO7fIPqLlHB9J2hJ7rGhZ5rilhuufylr4RXYPzJUeFjKxz305OsNlA==", "requires": { "lodash.capitalize": "^4.2.1", "lodash.escaperegexp": "^4.1.2", @@ -749,9 +705,9 @@ "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" }, "npm-run-path": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.0.tgz", - "integrity": "sha512-8eyAOAH+bYXFPSnNnKr3J+yoybe8O87Is5rtAQ8qRczJz1ajcsjg8l2oZqP+Ppx15Ii3S1vUTjQN2h4YO2tWWQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", "requires": { "path-key": "^3.0.0" } @@ -795,9 +751,9 @@ } }, "p-finally": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz", - "integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" }, "p-map": { "version": "2.1.0", @@ -845,9 +801,9 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" }, "picomatch": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.1.1.tgz", - "integrity": "sha512-OYMyqkKzK7blWO/+XZYP6w8hH0LDvkBvdvKukti+7kqYFCiEAk+gI3DWnryapc0Dau05ugGTy0foQ6mqn4AHYA==" + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz", + "integrity": "sha512-ISBaA8xQNmwELC7eOjqFKMESB2VIqt4PPDD0nsS95b/9dZXvVKOlz9keMSnoGGKcOHXfTvDD6WMaRoSc9UuhRA==" }, "pump": { "version": "3.0.0", @@ -1008,11 +964,6 @@ "path-key": "^2.0.0" } }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" - }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",